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 <
Another way to do it:
handleChange({ target }) {
this.props.someCallback(
Array.prototype.slice.call(target.selectedOptions).map(o => o.value)
)
}
In the case you would like to keep track of the selected options while the form is being completed:
handleChange(e) {
// assuming you initialized the default state to hold selected values
this.setState({
selected:[].slice.call(e.target.selectedOptions).map(o => {
return o.value;
});
});
}
selectedOptions
is an array-like collection/list of elements related to the DOM. You get access to it in the event target object when selecting option values. Array.prototype.slice
and call
allows us to create a copy of it for the new state. You could also access the values this way using a ref (in case you aren't capturing the event), which was another answer for the question.
Easiest way...
handleChange(evt) {
this.setState({multiValue: [...evt.target.selectedOptions].map(o => o.value)});
}
The following worked for me
var selectBoxObj = React.findDOMNode(this.refs.selectBox)
var values = $(selectBoxObj).val()
Try this one:
dropdownChanged = (event) => {
let obj = JSON.parse(event.target.value);
this.setState(
{
key: obj.key,
selectedName: obj.name,
type: obj.type
});
}
<select onChange={this.dropdownChanged} >
<option value={JSON.stringify({ name: 'name', key: 'key', type: "ALL" })} >All Projetcs and Spaces</option></select>
In case you want to use ref
you can get selected values like this:
var select = React.findDOMNode(this.refs.selectRef);
var values = [].filter.call(select.options, function (o) {
return o.selected;
}).map(function (o) {
return o.value;
});
2018 ES6 update
let select = this.refs.selectRef;
let values = [].filter.call(select.options, o => o.selected).map(o => o.value);