score:3

Accepted answer

I would suggest using a single data flow pattern (like Flux or Reflux) to structure your react apps and avoid that kind of mistake and complicated reverse data flows.

From what I understood of your question, without Flux, you could do something like this.

var React = require("react");

var ParentComponent = React.createClass({
    handleChange: function(newOption){
        console.log("option in child component changed to " + newOption);
    },
    render: function(){
        return (
            <div>
                <ChildComponent handleChange={this.handleChange}/>
            </div>
        )
    }
});

var ChildComponent = React.createClass({
    getInitialState: function(){
        return {
            selectedOption: 0
        };
    },
    handleChange: function(){
        var option = this.refs.select.getDOMNode().value;
        this.setState({ selectedOption: option});
        // I'm passing the actual value as an argument,
        // not this.state.selectedOption
        // If you want to do that, do it in componentDidUpdate
        // then the state will have been set
        this.props.handleChange(option);
    },
    render: function(){
        return (
            <div>
                <h4>My Select</h4>
                {this.state.selectedOption}
                <select ref="select"
                        onChange={this.handleChange}>
                    <option>1</option>
                    <option>2</option>
                    <option>3</option>
                </select>
            </div>
        )
    }
});

Edit Added a couple of forgotten semi-colons. I'm coding too much Python these days.

Edit2 Changed the code. Your problem might be that if you call the parent's handleChange with the value from the state (this.state.selectedOption), the state won't be set yet so you have to give the actual value as an argument instead. If you really want to use this.state.selectedOption, call parent's handleChange in componentDidUpdate.


Related Query

More Query from same tag