Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React.js onChange make the parent aware of the changed state

I have a component that is rendering <select> with <option> elements. When any change occurs, I would like to change the state of the component to keep the value of the currently selected option. As far as I know I don't have any other alternative for keeping this value since the props in React JS have to be immutable.

The problem comes when I notify the parent for the change. I do this using a callback from handleChange to parent's handleChangefunction. So in the child element I actually call the handleChangefunction, set the new state and call the callback (parent's handleChange). But then in the parent function when I ask for the value of the state property I receive the older one (seems like the new one is still not set).

So any ideas?

like image 711
Galya Avatar asked Oct 19 '22 14:10

Galya


1 Answers

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.

like image 198
Felix D. Avatar answered Oct 22 '22 04:10

Felix D.