javascriptreactjsreact-dom

Get the root DOM node of a React application


findDOMNode can be used to find the DOM node of a given Component, but I'm not sure how to traverse the tree to find the same node that was passed initially to ReactDOM.render().

e.g.

Discover the element root from inside App, where we have:

ReactDOM.render(
  <App />,
  document.getElementById('root')
);

Does React store this internally?


Solution

  • Technically there might be multiple React application running on the same page (different versions / microfrontends) and so, I don't know of a why from within a specific one of them to know which container belongs to it, but there is a way to find the root container, assuming it's a direct child node of the <body> element:

    const root = [...document.body.children].find(elem => elem._reactRootContainer)