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.