- read

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

John Au-Yeung 48

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

John Au-Yeung
JavaScript in Plain English
2 min read11 hours ago

--

Photo by NeONBRAND on Unsplash

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.

In Plain English

Thank you for being a part of our community! Before you go: