ReactDOM.render is no longer supported in React 18
Luigi Morel
Posted on April 5, 2022
So, I bootstrapped my first React application since the launch of React 18 (6 days after the launch).
When I checked my console, I was seeing an error that I did not expect to find (at least according to me):
Why the error occurs?
The error above is shown when you use React.render()
instead of React.createRoot
in React v18 to render the root of the application - which is always the div with an id of root in the index.js or index.tsx file; depending on whether you bootstrapped your application to use types (Typescript) or not.
How to fix.
Write the following code in your index.tsx
or index.js
file
- Import ReactDOM from the react-dom/client sub-module
Import ReactDOM from 'react-dom/client'
- Change the structure of your
index.js or index.tsx
file. However, this will depend on whether your using Typescript or not.
- Using Typescript
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App'
import reportWebVitals from './reportWebVitals'
const root = ReactDOM.createRoot(document.getElementById('root') as HTMLElement)
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
)
reportWebVitals()
Look closely and you'll see a createRoot somewhere. Had you seen it? 😏 Pay attention next time :)
The React team changes to createRoot so as to support
Concurrent Mode in React apps.
Concurrent Mode is a set of new features that help React apps stay responsive and gracefully adjust to the user’s device capabilities and network speed.
Read more about concurrent mode
- Using plain Javascript
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App'
import reportWebVitals from './reportWebVitals'
const root = ReactDOM.createRoot(document.getElementById('root'))
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
)
reportWebVitals()
Additional information.
- Using React Router in React 18
This is how you would set up your
index.js
orindex.tsx
file if you're using the new file set up.
import React from 'react'
import ReactDOM from 'react-dom/client'
import './index.css'
import App from './App'
import reportWebVitals from './reportWebVitals'
import { BrowserRouter } from 'react-router-dom'
const root = ReactDOM.createRoot(document.getElementById('root') as HTMLElement)
root.render(
<React.StrictMode>
<BrowserRouter>
<App />
</BrowserRouter>
</React.StrictMode>
)
reportWebVitals()
I hope I helped you in a way I could.
Cheers.
PS: This is the first article I've ever written. To growth 🎉
Posted on April 5, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.