You can include React using JavaScript file without adding the packages from HTML.
For example, the following HTML lines:
html<body> <script src = 'https://unpkg.com/react@17/umd/react.production.min.js'> <script src = 'https://unpkg.com/react-dom@17/umd/react-dom.production.min.js'> </body>
Are equivalent to:
javascriptconst script_1 = document.createElement('script') const script_2 = document.createElement('script') script_1.src = 'https://unpkg.com/react@17/umd/react.production.min.js' script_2.src = 'https://unpkg.com/react-dom@17/umd/react-dom.production.min.js' document.body.appendChild(script_1) document.body.appendChild(script_2)
Remember that you can use ReactDOM.render()
after the script has loaded:
javascriptscript_2.onload = function () { ReactDOM.render( <h1>Hello, world!</h1>, document.getElementById('root') ) }
Why would you want to do something like that? It's handy if you like to create a custom script, e.g. custom.js
, and you want to embed all the needed scripts into that file.
Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.