Don Rhummy Don Rhummy - 1 year ago 279
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

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?

Answer Source

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 {

        this.other = ReactDOM.render( <Hello name="World"/>, document.getElementById('otherComponent') );
        this.other.setState({lastName: "setState works"})
        this.other = ReactDOM.render( <Hello name="New Name" /> , document.getElementById('otherComponent') );
        return <div>
            <button onClick={this.changeState.bind(this)}>Change state</button>
            <button onClick={this.changeProps.bind(this)}>Change props</button>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download