React - access selected option on button click?
I have something like this
handleClick:function(){
// click logic
},
render: function(){
return (
<select>
<option value="a">A</option>
<option value="b">B</option>
</select>
<button onClick={this.handleClick}>Get Selected Value</button>
);
}
How do I get the value of an element select
when clicked button
?
+3
source to share
2 answers
You add a link to the selection
handleClick:function(){
var value = React.findDOMNode(this.refs.mySelect).value;
},
render: function(){
return (
<select ref="mySelect">
<option value="a">A</option>
<option value="b">B</option>
</select>
<button onClick={this.handleClick}>Get Selected Value</button>
);
}
+3
source to share
While you can get the DOM node to select and find out the current value, I find it easier to use component state for that. Something like that:
var React = require('react/addons');
var App = React.createClass({
mixins: [React.addons.LinkedStateMixin],
getInitialState: function () {
return {
option: 'a'
};
},
handleClick: function () {
alert(this.state.option);
},
render: function () {
return (
<select valueLink={this.linkState('option')}>
<option value="a">A</option>
<option value="b">B</option>
</select>
<button onClick={this.handleClick}>Get Selected Value</button>
);
}
});
Mixing LinkedStateMixin
ensures that any changes to the selection box automatically synchronize this value with the state of the components. But vice versa, you can update the state, and LinkedStateMixin
will make sure that the select box receives a new value.
0
source to share