2

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

You Nguyen
  • 9,961
  • 4
  • 26
  • 52
  • Possible if you get access to the react instance. During dev, the react-dev tools uses the same technique to get itself attached to the react instance and show you the data. But for prod this is disabled default. So if you ask me, without touching the code.. no. But if you get to add a single variable inside their code to point to a window variable, you can trigger it. – Panther May 07 '20 at 07:08
  • @Panther I can't access to the react instance. In fact, I don't know how to do that. Is it possible to find which React instance is currently binding to the `
    `
    – You Nguyen May 07 '20 at 08:38
  • Im afraid so.. If that is easy, it would lead to lot of security issue & exploits to be written. right.. – Panther May 08 '20 at 01:42
  • related to https://stackoverflow.com/q/56808847/104380 – vsync Dec 21 '22 at 17:44

2 Answers2

0

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.

Lior Hai
  • 477
  • 2
  • 5
  • I'm unable to access to their React code. What I'm doing is writing another layer of code on top of their React code. – You Nguyen May 07 '20 at 08:39
0

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.

Eddy Vinck
  • 410
  • 1
  • 4
  • 16
  • I'm unable to access to their React code. What I'm doing is writing another layer of code on top of their React code. – You Nguyen May 07 '20 at 08:39
  • in that case, you might be able to remount the entire app? maybe this helps? https://reactjs.org/blog/2015/10/01/react-render-and-top-level-api.html – Eddy Vinck May 07 '20 at 10:17