Search code examples
javascriptinternet-explorerreactjshtml-selectinternet-explorer-10

What is the proper way to get the value of a React <select> element?


Say I have the following React element (example fiddle here):

var Hello = React.createClass({
    getInitialState: function() {
        return {parsed: false};
    },
    _parseEvent: function(event) {
        var parser1 = event.currentTarget.selectedOptions[0].value;
        var parser2 = event.target.value;
        var parser3 = event.nativeEvent.srcElement.value;
        if (parser1 && parser2 && parser3)
            this.setState({parsed: true});
    },
    render: function() {
        var parsing = "parsing worked";
        return (
        <div>
        <select            
            onChange={this._parseEvent}>
            <option value="----">----</option>
            <option value="Yes">Yes</option>
            <option value="No">No</option>
        </select>
        <p>
        { this.state.parsed ?
        {parsing}
        : null}
        </p>
        </div>
        );
    }
});

React.render(<Hello name="World" />, document.getElementById('container'));

I'm using three ways of parsing the value of the <select> element. The first does not work on IE 10, and I know it's a bug per my question here. However, of the other two ways, parser2 or parser3, which is the proper way to get the value of a <select> element in React? Why? Thanks for any help!


Solution

  • Use what you would use in a W3C compatible browser:

    event.target.value
    

    This is also agnostic to the type of the form control element.