Home > Enterprise >  ReactJS - call function from broswer
ReactJS - call function from broswer

Time:12-29

I starting working with React and just converting an older web application into ReactJS.

My problem is that I load some content which later is added into a modal (dangerouslySetInnerHTML). The content includes <input type="button" onclick="myFunc()">

Previously I can just write a global function myFunc() and this was executed. But with ReactJS I don't know how to do this. If I just write this function into the component I getting myFunc is not defined.

Someone an idea how to solve it ?

Many thanks in advance

CodePudding user response:

I suggest using some kind of state management tool like Context or Redux. That way you can set a global function witch can be executed from anywhere in the app.

CodePudding user response:

First of all as the comment suggested, it is better to render the modal in react too instead of using dangerouslySetInnerHTML. Then consider that in react, when the project becomes really big it's prefered to use a state management tool as the answer above suggests. In case you are not considering to use a tool like this, the best practice is to keep the state on top of the element tree and pass it down (along with the functions which mutates it). So the solution to your question is basically definining the function on the component which holds the state you want to mutate and pass it down as props. Check this article for more info: https://reactjs.org/docs/faq-functions.html

CodePudding user response:

You can write global functions in react. Somewhere inside the class, maybe in the constructor or in componentDidMount or something, just write window.myFunc = this.myFunc.bind(this);

  • Related