Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does ReactDOM.render() render anything but ReactDOM.createRoot().render() does not?

I am trying to use JSX in React but ReactDOM.createRoot().render() won’t render anything:

import React from 'react'
import ReactDOM from 'react-dom'

ReactDOM.createRoot(root).render(<h1>Hello world</h1>)

But when i use ReactDOM.render it works:

import React from 'react'
import ReactDOM from 'react-dom'

ReactDOM.render(<h1>Hello world</h1>, root)

It is not like I have a problem with this, but I am more interested why it is this way.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Note: I am using React v17.0.2 and root refers to <div id="root"></div>.

>Solution :

ReactDOM.createRoot wasn’t added until v18. If you look in the devtools console, you should see this error:

TypeError: ReactDOM.createRoot is not a function

Here’s a v17 example showing the error:

const root = document.getElementById("root");
ReactDOM.createRoot(root).render(<h1>Hello world</h1>);
<div id="root"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.development.js"></script>

And a v18 example that works using createRoot:

const root = document.getElementById("root");
ReactDOM.createRoot(root).render(<h1>Hello world</h1>);
<div id="root"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>

For v17, use ReactDOM.render. (Or upgrade to v18 and use createRoot.)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading