The React way to set which option is selected for a select box, is to set a special value
prop on the itself, corresponding to the <
The same way you do anywhere else, since you're working with the real DOM node as the target of the change event:
handleChange: function(e) {
var options = e.target.options;
var value = [];
for (var i = 0, l = options.length; i < l; i++) {
if (options[i].selected) {
value.push(options[i].value);
}
}
this.props.someCallback(value);
}
With Array.from()
and e.target.selectedOptions
you can perform a controlled select-multiple:
handleChange = (e) => {
let value = Array.from(e.target.selectedOptions, option => option.value);
this.setState({values: value});
}
target.selectedOptions return a HTMLCollection
https://codepen.io/papawa/pen/XExeZY
You can actually find the selectedOptions
inside the target... no need to iterate over all the options. Let's imagine you want to send the values to an onChange
function passed to your component as props: you can use the following function on the onChange
of your multiple select.
onSelectChange = (e) => {
const values = [...e.target.selectedOptions].map(opt => opt.value);
this.props.onChange(values);
};