Categories
React Answers

How to Retrieve Values from a Select Element with Multiple Options in React?

Spread the love

Sometimes, we want to retrieve values from a select element with multiple options in React.

In this article, we’ll look at how to retrieve values from a select element with multiple options in React.

Retrieve Values from a Select Element with Multiple Options in React

To retrieve values from a select element with multiple options in React, we can get the selected values from the e.target.selectedOptions property.

For instance, we can write:

import { useState } from "react";

export default function App() {
  const [val, setVal] = useState([]);

  const handleChange = (e) => {
    const value = Array.from(
      e.target.selectedOptions,
      (option) => option.value
    );
    setVal(value);
  };

  return (
    <div className="App">
      <select multiple value={val} onChange={handleChange}>
        <option value={1}>First option</option>
        <option value={2}>Second option</option>
        <option value={3}>Third option</option>
      </select>
    </div>
  );
}

We create the val state to store the selected values with the useState hook.

Then we create the handleChange function to get the values from the e.target.selectedOptions by calling Array.from with a callback to map them to the value of each option selected.

e.target.selectedOptions has the selected options.

We then call setVal with value to set val to value .

Then finally, we add the select element with the multiple prop to let us pick multiple options.

We also set the value prop to val to let us see the values we selected.

And we set onChange to handleChange to set val to the updated variables.

Conclusion

To retrieve values from a select element with multiple options in React, we can get the selected values from the e.target.selectedOptions property.

Leave a Reply

Your email address will not be published. Required fields are marked *