How can I change the state of a React component from my old legacy jQuery soup code?
I have a component like this:
var AComponent = React.createClass({
getInitialState: function() {
return { ids: [] }
},
render: function() {
...
},
onButtonClick: function() {
ids.splice(…); // remove the last id
}
});
When something special happens in the old jQuery soup code, I'd like to
push an id to AComponent.state.ids
. How can I do that?
One "obvious" solution is an anti-pattern; here it is:
var componentInstance = AComtonent({});
React.renderComponent(componentInstance, document.getElementById(...));
// Somewhere else, in the jQuery soup. Something special happens:
componentIntance.state.ids.push(1234);
componentIntance.setState(componentInstance.state);
This is an antipattern, according to this email from a Facebook
developer,
because he writes that componentInstance
might be destroyed by React.
Always use the setState() method to change the state object, it will ensure that the component knows its been updated and calls the render() method (and all the other lifecycle methods).
You may call setState() immediately in componentDidUpdate() but note that it must be wrapped in a condition like in the example above, or you'll cause an infinite loop. It would also cause an extra re-rendering which, while not visible to the user, can affect the component performance.
Whoever worked or learned a bit of React probably knows that we should never change or update the state directly. Rather we should always declare a new object const obj = {} and use this. setState({ obj }) and let react handle it, just like I did in the example below.
Passing State to a Component To pass the state into another component, you can pass it as a prop. Then, inside <ExampleComponent /> , you can access the data as this. props.
I would make the component stateless. Store the ids
array outside of your component and pass it as a prop with functions that will modify the array. See example on JSFiddle: http://jsfiddle.net/ohvco4o2/5/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With