In this article, we will see how to create a dynamic dropdown list where the data is populated dynamically with the data received from the server.

Install the dependencies:

Let’s get started by installing the following dependencies i.e. react-bootstrap.

npm install react-bootstrap

Define the Dropdown component:

Now, let’s define the component which contains the dropdown menu. The component also has the logic which fetches the data from the server and fills the options state variable which is later used to create the items in the dropdown menu.

Example:

import React, { useState, useEffect } from 'react';
import { Dropdown } from 'react-bootstrap';

const DynamicDropdown = () => {
  const [options, setOptions] = useState([]);
  const [selectedOption, setSelectedOption] = useState('');

  useEffect(() => {
    // Fetch data from the server
    fetchData()
      .then((data) => {
        setOptions(data);
      })
      .catch((error) => {
        console.error('Error fetching data:', error);
      });
  }, []);

  const fetchData = async () => {
    // Make an API call to fetch the data from the server
    const response = await fetch('YOUR_API_ENDPOINT');
    const data = await response.json();
    return data;
  };

  const handleDropdownChange = (option) => {
    setSelectedOption(option.label);
  };

  return (
    <Dropdown>
      <Dropdown.Toggle variant="primary" id="dropdown-basic">
        {selectedOption || 'Select an option'}
      </Dropdown.Toggle>

      <Dropdown.Menu>
        {options.map((option) => (
          <Dropdown.Item
            key={option.id}
            onClick={() => handleDropdownChange(option)}
          >
            {option.label}
          </Dropdown.Item>
        ))}
      </Dropdown.Menu>
    </Dropdown>
  );
};

In the above example, replace the API_ENDPOINT with the server URL from which you want to fetch the data. This could be a REST API or any other server-side endpoint that returns the options for the dropdown list.

The setSelectedOption option in the above example is used to keep track of the currently selected option in the dropdown. The handleDropdownChange function is called when a dropdown option is selected. It updates the selectedOption state with the label of the selected option.

Render the component

Finally, render the <DynamicDropdown /> component at your desired location.

function App() {
  return (
    <div className="App">
      <h1>Dynamic Dropdown List with Data from Server</h1>
      <DynamicDropdown />
    </div>
  );
}

export default App;

Categorized in:

Tagged in: