DEV Community

Cover image for How can I set the value of a select input in React?
Isabelle M.
Isabelle M.

Posted on • Originally published at 30secondsofcode.org

1 1

How can I set the value of a select input in React?

Adding selected to an option

A very common way of setting a <select> input's value is by adding a selected attribute to one of its <option> elements. For example:

const Select = ({ values, callback, selected }) => {
  return (
    <select
      disabled={disabled}
      readOnly={readonly}
      onChange={({ target: { value } }) => callback(value)}
    >
      {values.map(([value, text]) => (
        <option selected={selected === value} value={value}>
          {text}
        </option>
      ))}
    </select>
  );
}
Enter fullscreen mode Exit fullscreen mode

Setting value for the select

While this approach closely resembles HTML and feels intuitive, there is an easier way to do the same thing. React provides us with a shared API between <input type="text">, <textarea> and <select> where we can use value or defaultValue (depending if the input is controlled or not) to set the field's value.

Using this API, we minimize the effort of checking for the selected value, as well as making the code easier to read and update as necessary. Here's an example:

const Select = ({ values, callback, selected }) => {
  return (
    <select
      disabled={disabled}
      readOnly={readonly}
      defaultValue={selected}
      onChange={({ target: { value } }) => callback(value)}
    >
      {values.map(([value, text]) => (
        <option value={value}>
          {text}
        </option>
      ))}
    </select>
  );
}
Enter fullscreen mode Exit fullscreen mode

Note that the above implementation uses defaultValue, therefore it implies that the component is uncontrolled. You can convert this Select component into a controlled component by using value instead of defaultValue.


Do you like short, high-quality code snippets and articles? So do we! Visit 30 seconds of code for more articles like this one or follow us on Twitter for daily JavaScript, React and Python snippets! 👨‍💻

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay