how to use setProps in react.js

I want to call setProps from outside of myComponent to be able to dynamically change data for myComponent.
I expect that after changing props of the component, it will re-render itself.

I was trying the following:

var myComponent = React.createClass({
  render: function () {
    return (
      React.DOM.div(null, this.props.data)
    );
  }
});

React.renderComponent(
  myComponent({ data: someData }),
  document.getElementById('predictionContent')
);

myComponent.setProps({data: someData2});

The problem is that I don’t understand how to use setProps for the component.
In my case, I receive “undefined” error.

How to solve this?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

warning: setProps is now deprecated.

React.createClass returns a class, it is React.renderComponent which returns an instance of the class which has the setProps method.

Try this instead:

var MyComponent = React.createClass({
    render: function () {
        return React.DOM.div(null, this.props.data);
    }
});

var myComponent = React.renderComponent(
     new MyComponent({ data: someData }),
     document.getElementById('predictionContent')
);

myComponent.setProps({ data: someData2 });

Having said that, Chad Scira’s answer is also correct: probably better to re-render than to call setProps. That will keep it looking the same as the code inside the render() method, and you’ll always be able to call renderComponent, regardless of whether it is the first time or a subsequent update.

Like this:

var MyComponent = React.createClass({
    render: function () {
        return React.DOM.div(null, this.props.data);
    }
});

React.renderComponent(
     new MyComponent({ data: someData }),
     document.getElementById('predictionContent')
);

// later
React.renderComponent(
     new MyComponent({ data: someData2 }),
     document.getElementById('predictionContent')
);

Method 2

You’re not supposed to do that. Instead just run the renderComponent method again like this:

React.renderComponent(
     myComponent({ data: someData2 }),
     document.getElementById('predictionContent')
);

react will automatically resolve the differences


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x