Skip to content
react

How to fix ReactDOM.render is no longer supported in React 18

Apr 5, 2022Abhishek EH2 Min Read
How to fix ReactDOM.render is no longer supported in React 18

If you have recently upgraded your react version to 18 or initialized an application using create react app, you would have seen the following warning in the browser console:

Warning: ReactDOM.render is no longer supported in React 18. Use createRoot instead. Until you switch to the new API, your app will behave as if it's running React 17.

warning

In this article, we will see why this warning appears and how to fix it.

React has recently released version 18. In the latest version, it has introduced createRoot API, which is used to support new React features.

createRoot API will replace the ReactDOM.render, which was present in the previous versions. Hence we are getting a warning.

You can see what needs to be updated in the diff below:

index.js
1import React from "react";
2- import ReactDOM from "react-dom";
3+ import { createRoot } from "react-dom/client";
4import "./index.css";
5import App from "./App";
6import reportWebVitals from "./reportWebVitals";
7
8+ const container = document.getElementById("root");
9+ const root = createRoot(container);
10
11- ReactDOM.render(
12- <React.StrictMode>
13- <App />
14- </React.StrictMode>,
15- document.getElementById("root")
16- );
17
18+ root.render(
19+ <React.StrictMode>
20+ <App />
21+ </React.StrictMode>
22+ );
23
24// If you want to start measuring performance in your app, pass a function
25// to log results (for example: reportWebVitals(console.log))
26// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
27reportWebVitals();

The updated code will be:

index.js
1import React from "react"
2import { createRoot } from "react-dom/client"
3import "./index.css"
4import App from "./App"
5import reportWebVitals from "./reportWebVitals"
6
7const container = document.getElementById("root")
8const root = createRoot(container)
9
10root.render(
11 <React.StrictMode>
12 <App />
13 </React.StrictMode>
14)
15
16// If you want to start measuring performance in your app, pass a function
17// to log results (for example: reportWebVitals(console.log))
18// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
19reportWebVitals()

Now if you reload the page, you should not see the warning in the console.

Do follow me on twitter where I post developer insights more often!

© 2024 CodingDeft.Com