Categories
React Answers

How to retrieve value from select with multiple option in React?

Spread the love

Sometimes, we want to retrieve value from select with multiple option in React.

in this article, we’ll look at how to retrieve value from select with multiple option in React.

How to retrieve value from select with multiple option in React?

To retrieve value from select with multiple option in React, we can get the selected options from the element’s selectedOptions property.

For instance, we write

const Comp = () => {
  const [arrayOfOptionValues, setArrayOfOptionValues] = useState();

  const onSelectChange = (e) => {
    const values = [...e.target.selectedOptions].map((opt) => opt.value);
    setArrayOfOptionValues(values);
  };

  //...

  return (
    <select multiple value={arrayOfOptionValues} onChange={handleChange}>
      <option value={1}>First option</option>
      <option value={2}>Second option</option>
      <option value={3}>Third option</option>
    </select>
  );
};

to define the arrayOfOptionValues state with the useState hook.

Then we add the onSelectChange function that gets the selected options from e.target.selectedOptions.

We then spread that into an array and call map to get the values.

Next, we call setArrayOfOptionValues to set the values as the value of arrayOfOptionValues.

Finally, we add a select element that takes multiple values and set the value prop to arrayOfOptionValues and the onChange prop to the handleChange function.

Then then selected options are set as the value of arrayOfOptionValues when they change.

Conclusion

To retrieve value from select with multiple option in React, we can get the selected options from the element’s selectedOptions property.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.