3

Is it okay if I insert React component directly in document body by id?

Or it is better to wrap it in DIV?

index.js

ReactDOM.render(
    <Provider store={store()}>
        <App/>
    </Provider>,
    document.querySelector("#root")
)

index.html

<body class="d-flex flex-column h-100" id="root">
  <noscript>You need to enable JavaScript to run this app.</noscript>
</body>

2 Answers2

2

I don't recommend to use body as root of the virtual DOM for 3 reasons:

  1. body normally contains script tags, which might include your React logic. Rerendering body means that you need to take care of all your scripts too, and everytime body needs to be re-rendered, all your scripts need to be reload again, which is not efficient, not to mention side effect of reloading React code (which I don't have any experience to justify). The only way to avoid this is to put all your scripts into header, which is not recommended.
  2. If you need to modify body, e.g. adding classes "modal-open" if you use Bootstrap modal, there are other solutions like using React's hook or an event listener dedicated to updating body.
  3. Normally a web application product does not only use a DOM manipulator script, but also other scripts for business purposes (e.g. Google Analytics, Analytics.js, Google map). There are apps which contains more than 1 React script working independently. In those cases, the script logic should be separated and not coupled together. If there are 2 React scripts, the 2 root nodes should not be nested to avoid unneeded re-render.
blaz
  • 3,981
  • 22
  • 37
0

In my html page I only use one <div id="root">

After that:

ReactDOM.render(element, document.getElementById('root'));

does all the magic.

reference: https://reactjs.org/docs/rendering-elements.html

Jose Cabrera Zuniga
  • 2,348
  • 3
  • 31
  • 56