React - Accessing Selected Option On Button Click?
I have something like this handleClick:function(){ // click logic }, render: function(){ return (
Solution 1:
You add a reference to the select
handleClick:function(){
var value = React.findDOMNode(this.refs.mySelect).value;
},
render: function(){
return (
<selectref="mySelect"><optionvalue="a">A</option><optionvalue="b">B</option></select><buttononClick={this.handleClick}>Get Selected Value</button>
);
}
Solution 2:
While you can get a hold of the DOM node of the select and find out the current value, I find it simpler to use component state for this. Something like this:
varReact = require('react/addons');
varApp = React.createClass({
mixins: [React.addons.LinkedStateMixin],
getInitialState: function () {
return {
option: 'a'
};
},
handleClick: function () {
alert(this.state.option);
},
render: function () {
return (
<selectvalueLink={this.linkState('option')}><optionvalue="a">A</option><optionvalue="b">B</option></select><buttononClick={this.handleClick}>Get Selected Value</button>
);
}
});
The LinkedStateMixin
mixin makes sure that any changes to the select box will automatically sync that value to the components state. But also the other way around, you can update the state and LinkedStateMixin
will make sure that the select box gets the new value.
Post a Comment for "React - Accessing Selected Option On Button Click?"