Don Rhummy Don Rhummy - 3 months ago 14
React JSX Question

In React, how can a parent change prop or state values on another component programatically?

I have created and rendered another component. On a button click, I want to do some calculations and then change some props on that other component so it will update its view. How would I do this?

If they need to be state values instead of props, that's ok. Can the

setState()
be called from another component?

class MainComponent extends React.Component {

other: null,

constructor(props, children)
{
//Create the component
this.other = ReactDOM.render( otherReactElement, document.body );
}

...

//An on Click handler
handle: function(evt)
{
//This is what I want to do
other.setProps( { aPropToChange: "new value" } );
}
};


The "setProps" is deprecated. What else can I do to enable something like that?

QoP QoP
Answer

If you want to pass new props to other, you have to call ReactDOM.render() again with the new props as you can see here.

I have created a jsfiddle where you can see how to update the props and the state correctly.

class MainComponent extends React.Component {

    constructor(props)
    {
        super(props);
        this.other = ReactDOM.render( <Hello name="World"/>, document.getElementById('otherComponent') );
    }
    changeState(evt)
    {
        this.other.setState({lastName: "setState works"})
    }
    changeProps(evt){
        this.other = ReactDOM.render( <Hello name="New Name" /> , document.getElementById('otherComponent') );
    }
    render(){
        return <div>
            <button onClick={this.changeState.bind(this)}>Change state</button>
            <button onClick={this.changeProps.bind(this)}>Change props</button>
            </div>
    }
};
Comments