Responsive Advertisement

How do I create a dynamic search filter in an HTML dropdown with React?

 

React UseEffect and UseState

How do I create a dynamic search filter in an HTML dropdown with React?

To create a dynamic search filter in an HTML dropdown with React, you can use a combination of the useState and useEffect hooks to manage the state of the dropdown and the filter text. Here's an example of how you can do this:

import React, { useState, useEffect } from 'react';

const options = [
  'Apple',
  'Banana',
  'Cherry',
  'Durian',
  'Elderberry',
  'Fig',
  'Grapefruit',
  'Honeydew',
  'Kiwi',
  'Lemon',
];

const Dropdown = () => {
  const [filterText, setFilterText] = useState('');
  const [filteredOptions, setFilteredOptions] = useState(options);

  useEffect(() => {
    setFilteredOptions(options.filter(option =>
      option.toLowerCase().includes(filterText.toLowerCase())
    ));
  }, [filterText]);

  const handleChange = e => {
    setFilterText(e.target.value);
  };

  return (
    <div>
      <input type="text" placeholder="Search..." value={filterText} onChange={handleChange} />
      <select>
        {filteredOptions.map(option => (
          <option key={option} value={option}>{option}</option>
        ))}
      </select>
    </div>
  );
};

In this example, we're defining an array of options and using the useState hook to manage the state of the filter text and the filtered options. We're also using the useEffect hook to filter the options whenever the filter text changes.

The handleChange function updates the filterText state whenever the user types in the search input. The useEffect hook filters the options based on the current filterText state and updates the filteredOptions state.

We're then rendering an input field to allow the user to type in the search text, and a select dropdown to display the filtered options. The filteredOptions state is mapped over to render each option in the dropdown as an HTML option element.

With this approach, the options displayed in the dropdown will be filtered dynamically based on the text entered in the search input.


Post a Comment

0 Comments