Categories
React Answers

How to Retrieve the Value From a Muti-Select Element in React?

Spread the love

Sometimes, we want to retrieve the value from a multi-select element in React.

In this article, we’ll look at how to retrieve the value from a multi-select element in React.

Retrieve the Value From a Muti-Select Element in React

To retrieve the value from a multi-select element in React, we can get the selected values from the e.target.selectedOptions property.

For instance, we can write:

import React, { useState } from "react";

export default function App() {
  const [values, setValue] = useState([]);
  const handleChange = (e) => {
    const value = [...e.target.selectedOptions].map((option) => option.value);
    setValue(value);
  };

  return (
    <div>
      <select onChange={handleChange} multiple>
        <option value={1}>apple</option>
        <option value={2}>orange</option>
        <option value={3}>grape</option>
      </select>
      <p>{values.toString()}</p>
    </div>
  );
}

We defined the values state with the useState hook.

Then we defined the handleChange function that spreads the e.target.selectedOptions property into an array.

And then we call map to get the value property from each selected item.

Finally, we add the select element with the multiple prop to add a multi-select dropdown.

And we display the values below that.

Now when we select from the multi-select box, we see the value prop of the selected option element displayed.

Conclusion

To retrieve the value from a multi-select element in React, we can get the selected values from the e.target.selectedOptions property.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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