Categories
React Answers

How to Listen to the Drop Down’s Change Event in React?

Spread the love

Sometimes, we want to listen to the drop down’s change event in React.

In this article, we’ll look at how to listen to the drop down’s change event in React.

Listen to the Drop Down’s Change Event in React

To listen to the drop down’s change event in React, we can set the onChange prop of the select element to the change event listener function.

For instance, we write:

import React, { useState } from "react";

const Dropdown = ({ options }) => {
  const [selectedOption, setSelectedOption] = useState(options[0].value);
  return (
    <select
      value={selectedOption}
      onChange={(e) => setSelectedOption(e.target.value)}
    >
      {options.map((o) => (
        <option key={o.value} value={o.value}>
          {o.label}
        </option>
      ))}
    </select>
  );
};

const options = [
  { value: "apple", label: "Apple" },
  { value: "orange", label: "Orange" },
  { value: "pear", label: "Pear" }
];

export default function App() {
  return <Dropdown options={options} />;
}

to define the Dropdown component that takes an array of options.

In the component, we define the selectedOption state, which is set to options[0].value initially, which is the value of the first option.

Then we set selectedOption as the value prop’s value.

And we set onChange to a function that calls setSelectedOption with e.target.value to set selectedOption to the value attribute’s value of the selected option.

In the select element, we render the option elements from the options array.

Finally, in App, we add the Dropdown component and set options to an options array.

Conclusion

To listen to the drop down’s change event in React, we can set the onChange prop of the select element to the change event listener function.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

One reply on “How to Listen to the Drop Down’s Change Event in React?”

Love this article, it helped me to understand something in a bind, I would help if you had a link to either a github repo or a sandbox with this code shown

Leave a Reply

Your email address will not be published. Required fields are marked *