0
0
ReactDebug / FixBeginner · 4 min read

How to Handle Select Dropdown in React: Controlled Component Example

In React, handle a 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.

jsx
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;
Output
The dropdown renders but selecting an option does not update React state or reflect changes in the UI properly.
🔧

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.

jsx
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;
Output
The dropdown shows 'Apple' selected initially and updates the selected option visibly and in React state when changed.
🛡️

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 value prop on select, causing it to be uncontrolled.
  • Forgetting to update state in onChange, so the UI doesn't reflect user selection.
  • Using defaultValue instead of value in controlled components, which leads to inconsistent behavior.

Key Takeaways

Use React state to control the select dropdown value for predictable UI updates.
Always update state inside the onChange handler to reflect user choices.
Add accessibility attributes like aria-label for better screen reader support.
Avoid mixing controlled and uncontrolled inputs to prevent bugs.
Use linting tools to catch common React form handling mistakes early.