How to trigger React to re-render from outside

Viewed 661

Is there anyway for us to trigger React to re-render from the outside?

The situation is I'm developing a chrome extension which directly mutate the DOM, that technique cause the Virtual DOM of React confused. So I need to figure out a way to trigger the React to re-render the whole page. The website that I'm targeting is a web chat (similar to Messenger) which is a SPA powered by React. I can't do anything with their React code but only can build another layer of code on top of their code.

Is this idea technically impossible? Is there anyway to trick React to re-render from the outside. (by outside, I mean without touching the React code of the website).

2 Answers

If you are using hooks, you could probably do this with the useEffect hook

export const App = () => {
    useEffect(() => {
         // do something that triggers a re-render, like setting state
    }, [window.reactTimestamp])
}

and then somewhere in your app, when you wawnt to update

window.reactTimestamp = Date.now()

I haven't tested it, but I believe this should work.

I didn't test it, but a solution can be to expose internal function to window. In some X component, do window.refreshApp = this.refreshApp. and refreshApp function will use setState with a counter increase to cause the re-render.

Related