Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change state of React component from old external Javascript?

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.

like image 268
KajMagnus Avatar asked Sep 24 '14 20:09

KajMagnus


People also ask

How do you change the state of any React component?

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).

Can we set state in component did update?

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.

Can you update state directly React?

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.

How do you pass a state from one component to another React native?

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.


1 Answers

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/

like image 158
kulesa Avatar answered Sep 30 '22 06:09

kulesa