Search code examples
javascriptreactjsdomdocumentreact-dom

Does ReactDOM.render wait for the document to be loaded before rendering?


I'm wondering if I need to wait for the document to be loaded (i.e. listen to DOMCOntentLoaded) before calling ReactDOM.render(...). It doesn't seem like other React example apps are doing so, so I'm guessing inside the implementation of ReactDOM.render they already wait?


Solution

  • You just need to ensure that the DOM element that your react code renders into is available at the time the <script> is evaluated. You can do this by placing the script after the dom element in your index.html file.

    <!-- this will work -->
    <div id="react-app"></div>
    <script type="text/javascript" src="./my-react-script.js"></script>
    
    <!-- this will NOT work -->
    <script type="text/javascript" src="./my-react-script.js"></script>
    <div id="react-app"></div>