In React, when working with a select element that supports multiple selections (using the multiple attribute), it’s important to properly retrieve and manage the selected values. While React allows you to control the selected options via the value prop (using an array), the onChange event does not return the selected values directly in array form. Instead, you must manually extract them from the event.
The e.target.options property returns an HTMLOptionsCollection, which contains allelements inside the select tag. To obtain only the selected options:
This approach ensures accurate retrieval and alignment with React’s controlled component model.
var MultiSelectComponent = React.createClass({
handleChange: function(e) {
const selectedValues = Array.from(e.target.options)
.filter(option => option.selected)
.map(option => option.value);
this.props.someCallbackFromParent(selectedValues);
},
render: function() {
return (
<select multiple={true} value={this.props.arrayOfOptionValues} onChange={this.handleChange}>
<option value="1">First option</option>
<option value="2">Second option</option>
<option value="3">Third option</option>
</select>
);
}
});
import React from 'react';
const MultiSelectComponent = ({ arrayOfOptionValues, someCallbackFromParent }) => {
const handleChange = (e) => {
const selectedValues = Array.from(e.target.options)
.filter(option => option.selected)
.map(option => option.value); // or parseInt(option.value, 10) if numeric
someCallbackFromParent(selectedValues);
};
return (
);
};
Using this pattern, you can build reliable multi-select inputs in both class-based and functional React components.
Work with our skilled React developers to accelerate your project and boost its performance.
Hire Reactjs Developers