Change state of React component from old external Javascript?

How can I change the state of a React component from old old 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 happens in the old jQuery code, I would like to click id on AComponent.state.ids . How can i do this?

One β€œobvious” solution is an anti-pattern; there he 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 antipattern, according to this letter from the Facebook developer , because he writes that componentInstance can be destroyed by React.

+5
source share
1 answer

I would make the component standstill. Store the ids array outside of your component and pass it as a support with functions that will modify the array. See an example in JSFiddle: http://jsfiddle.net/ohvco4o2/5/

+4
source

Source: https://habr.com/ru/post/1203335/


All Articles