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

1k views Asked by At

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!

2

There are 2 answers

2
Felix Kling On BEST ANSWER

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.

2
Michael Parker On

While the other answer works just fine, if you're looking for a React way, then this can be accomplished by using refs.

Assign a ref to the select:

<select onChange={this._parseEvent} ref="select">
    <option value="----">----</option>
    <option value="Yes">Yes</option>
    <option value="No">No</option>
/select>

Get the DOM node via ref:

var node = React.findDOMNode(this.refs.select)

Get the value via DOM node:

var value = node.value;

Here's an updated fiddle to demonstrate: https://jsfiddle.net/ve88383c/4/