Answer the question
In order to leave comments, you need to log in
How to change state of react js component from outside?
The project needed to dynamically create and show a simple modal window on a button click.
The idea is this: when clicked, an event is generated, all listeners somehow react to it. Among them is a modal window component, which, based on the received data, renders the corresponding block or, if necessary, updates the data in it.
It would be possible to take any template engine, the same nunjucks, which is like my own, and create this same window.
But since in the future there will most likely be more complex elements in the project, I decided to take React js as a View, with which, however, I never worked at all.
It turned out something like this:
....
this.on('showModal', function (data) {
ReactDOM.render(
<this.renderWindow data={data} />,
this.el
);
});
....
Answer the question
In order to leave comments, you need to log in
Just subscribe to this event in the method componentDidMount
and change the state as you like.
Strange problem. React is a view, and we store all the state using the Flux architecture (redux, in this case). At the app level, we write a reducer that is responsible for the activity of the modal window. If the window is active - render it. I repeat, in react at the level of the entire application, we never do such hacks that are written above, but instead we store the entire state in the redux store. This is really handy for independent operations. And if you try to create this at the component level, then it's easier not to use react.
At first it seemed to me that this is a perversion - to use React, instead of a template engine, like from a cannon to sparrows.
But, in the use itself, in my opinion, there is nothing special - here I have collected a demo
for you
. In short:
If you use my component, then you need to change your code a little:
...
this.on('showModal', function (data) {
if (!window.modalAttached) {
ReactDOM.render(
<ModalWindow data={data} />,
this.el
)
}
window.toggleModal();
}
...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question