No Time Dad

A blog about web development written by a busy dad

Quick React Select Value Example

There are two types of React form components. Controlled and uncontrolled. I almost always use controlled components. They just makes managing the state easier, and it’s the preferred way in React to work with forms.

The form below is a react select value change example. It uses the React useState hook to set and update the selected value for the form. That same state value is then displayed below the form.

You're favorite color is: Blue
import React, { useState } from 'react';

export const Select = () => {
  const [value, setValue] = useState('Blue');

  const handleChange = (event) => {
    setValue(event.target.value);
  }

  return (
    <>
      <form>
        <label htmlFor="color">
          Pick your favorite color:
        </label>
        <select name="color" value={value} onChange={handleChange}>
          <option value="Blue">Blue</option>
          <option value="Green">Green</option>
          <option value="Red">Red</option>
          <option value="Purple">Purple</option>
        </select>
      </form>
      <div>You're favorite color is: {value}</div>
    </>
  );
}

An important thing to note with this design is that the onChange event handler is on the parent select element. It’s sometimes tempting to add the handler to each option, but that could have unexpected results.

The onChange function itself is automatically passed the event object, and looks at the event target’s value property to get the newly selected value. An alternative way and more explicit way to call the handleChange function is shown below. This approach is fine, but it just requires slightly more code.

<select ... onChange={(event) => handleChange(event)}>
  ...
</select>