How to Handle Select Dropdown in React: Controlled Component Example
select dropdown by making it a controlled component using useState to store the selected value and an onChange handler to update that state. This ensures React controls the dropdown value and updates the UI correctly.Why This Happens
When you use a select dropdown in React without controlling its value via state, React does not know which option is selected. This causes the dropdown to not update or behave unexpectedly because the component is uncontrolled.
import React from 'react'; function Dropdown() { return ( <select> <option value="apple">Apple</option> <option value="banana">Banana</option> <option value="cherry">Cherry</option> </select> ); } export default Dropdown;
The Fix
Use React's useState hook to store the selected value and set the value attribute of the select to that state. Add an onChange handler to update the state when the user picks a new option. This makes the dropdown a controlled component and keeps React in sync with the UI.
import React, { useState } from 'react'; function Dropdown() { const [selected, setSelected] = useState('apple'); const handleChange = (event) => { setSelected(event.target.value); }; return ( <select value={selected} onChange={handleChange} aria-label="Fruit selection"> <option value="apple">Apple</option> <option value="banana">Banana</option> <option value="cherry">Cherry</option> </select> ); } export default Dropdown;
Prevention
Always use controlled components for form inputs in React to keep UI and state in sync. Use useState or other state management to store input values and update them with onChange. Enable linting rules like react-hooks/rules-of-hooks and jsx-a11y/accessible-forms to catch common mistakes early.
Also, add aria-label or use semantic HTML to improve accessibility for screen readers.
Related Errors
Common related errors include:
- Not setting the
valueprop onselect, causing it to be uncontrolled. - Forgetting to update state in
onChange, so the UI doesn't reflect user selection. - Using
defaultValueinstead ofvaluein controlled components, which leads to inconsistent behavior.
Key Takeaways
select dropdown value for predictable UI updates.onChange handler to reflect user choices.aria-label for better screen reader support.