Deprecation notice: ReactDOM.render is no longer supported in React 18
Asked Answered
J

15

243

I get this error every time I create a new React app:

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. Learn more: https://reactjs.org/link/switch-to-createroot

How can I fix it?

I created my React app using:

npx create-react-app my-app
Jersey answered 29/3, 2022 at 20:11 Comment(1)
See Batching in ReactKisumu
C
408

In your file index.js, change to:

import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

reportWebVitals();

For TypeScript

Credit from comment section below answer: Kibonge Murphy

import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
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();
Cottrell answered 29/3, 2022 at 20:29 Comment(6)
For typescript support const root = ReactDOM.createRoot(document.getElementById("root") as HTMLElement);Windbound
@KibongeMurphy I get the following warning when adding what you recommended. This assertion is unnecessary since it does not change the type of the expression.sonarlint(typescript:S4325) Any ideas why?Gunzburg
The versions you're running would be helpful to understand what's happening... For now, it looks like you don't need the explicit casting. Try removing the as HTMLElementWindbound
For reference check this: reactjs.org/link/switch-to-createrootAlgetic
now i get react-dom.development.js:86 Warning: You are importing createRoot from "react-dom" which is not supported. You should instead import it from "react-dom/client"Darelldarelle
I get this warning from npx create-react-app and updating react and react-dom, running ǹpm audit fix [--force]` doesn't even fix the vulnerabilities. Who ships a broken version of React? What a fiasco.Epencephalon
Y
63

React 18 shipped March 29th, 2022. ReactDOM.render has been deprecated in React 18 and currently issues a warning and runs in a compatible mode.

Deprecations

Deprecations

  • react-dom: ReactDOM.render has been deprecated. Using it will warn and run your app in React 17 mode.
  • react-dom: ReactDOM.hydrate has been deprecated. Using it will warn and run your app in React 17 mode.
  • react-dom: ReactDOM.unmountComponentAtNode has been deprecated.
  • react-dom: ReactDOM.renderSubtreeIntoContainer has been deprecated.
  • react-dom/server: ReactDOMServer.renderToNodeStream has been deprecated.

To resolve it, you can either revert to a previous version of React or update your index.js file to align with the React 18 syntax.

Example:

import { StrictMode } from "react";
import { createRoot } from "react-dom/client";

import App from "./App";

const rootElement = document.getElementById("root");
const root = createRoot(rootElement);

root.render(
  <StrictMode>
    <App />
  </StrictMode>
);
Yearning answered 31/3, 2022 at 2:42 Comment(4)
This is a good answer. But if, like me, you're using Typescript, you will need to add something like ``` if (!rootElement) throw new Error('Failed to find the root element') ``` before calling createRoot.Clippard
For typescript users, the only thing you need to do is add "devDependencies": { "@types/react-dom": "^18.0.0" }. That's it. The code above with createRoot is fine.Turtledove
@matdev Yes, move whatever Link components you are rendering inside any router component you are rendering. This has nothing to do with React 18. See error useHref() may be used only in the context of a <Router> component. If you need more help from here it preferable to create a new SO post with the specific details and minimal reproducible example. Feel free to ping me here with a link to the post if you like, and I can take a look when available.Yearning
Or just const root = createRoot(document.getElementById('root')); for those of us who prefer fewer lines. (To replace lines 6 & 7.)Couch
D
40

Instead of:

import ReactDOM from 'react-dom'
ReactDom.render(<h1>Your App</h1>, document.getElementById('root'))

Use:

import { createRoot } from 'react-dom/client'
createRoot(document.getElementById('root')).render(<h1>Your App</h1>)

More details here

Drayage answered 25/4, 2022 at 3:18 Comment(0)
P
16

Before

import { render } from 'react-dom';
const container = document.getElementById('app');
render(<App tab="home" />, container);

After

import { createRoot } from 'react-dom/client';
const container = document.getElementById('app');
const root = createRoot(container);
root.render(<App tab="home" />);

Before in your index.js file:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);


reportWebVitals();

Change it like below into your index.js file:

import React from 'react';

import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

import { createRoot } from 'react-dom/client';
const container = document.getElementById('root');
const root = createRoot(container);
root.render(<React.StrictMode>
  <App />
</React.StrictMode>);


reportWebVitals();
Pinwork answered 6/4, 2022 at 7:34 Comment(1)
It is not easy to see the diff. And an explanation would be in order. E.g., what is the idea/gist? From the Help Center: "...always explain why the solution you're presenting is appropriate and how it works". Please respond by editing (changing) your answer, not here in comments (without "Edit:", "Update:", or similar - the answer should appear as if it was written today).Genital
D
10

The legacy root API with ReactDOM.render has been deprecated in React 18 and replaced with a new root API using createRoot. The root of your app is the top-level DOM element that contains all of your rendered components, and is usually a <div> with an ID of root.

React 18 still has support for ReactDOM.render so you technically aren't required to update, but you can't be sure how long this support will last.

You can find a lot more information on the difference between ReactDOM.render and createRoot at https://thelonecoder.dev/javascript/react-js/reactdom-render-vs-createroot/.

To update to the new root API, change your index.js file to something like the following:

import { createRoot } from 'react-dom/client';
import App from './App';

const root = createRoot(document.getElementById('root'));
root.render(<App />);
Dermatophyte answered 25/4, 2023 at 20:32 Comment(1)
The warning says your application is going to be behaving as React 17, is this not actually required to trigger the React 18 ?Ulrika
M
7

To provide more or less an equivalent to prior versions of React, I use this slightly condensed version of the above, still surrounding the <App> with the <React.StrictMode>.

Another reason I condense this is that - in my specific pipeline - I never need to access the root variable, consequently, chaining statements together makes more sense to me, and the whole file is just five lines of code:

import React from 'react';
import ReactDOM from "react-dom/client";

import './index.css';
import App from './App';

    ReactDOM.createRoot(document.querySelector("#root")).render(<React.StrictMode><App /></React.StrictMode>);

(P.S.: Don't forget if you need the webvitals functionality to also add to the above code)

Finally, I save this starter code as a Live Template using the WebStorm IDE. Depending on your IDE your snippets may be called differently, but the idea should be similar.

Melissiamelita answered 30/3, 2022 at 6:16 Comment(1)
your "runnable" code cannot run in Stackoverflow with import statementsXanthous
D
7

As you said, you created your React app using: npx create-react-app my-app.

Your index.js must look like this after the command executes:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

reportWebVitals();

Your code after edits mentioned in the console:

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

const container = document.getElementById('root');
const root = ReactDOM.createRoot(container);
root.render(<App />);

reportWebVitals();
Disperse answered 30/3, 2022 at 11:17 Comment(2)
your "runnable" code cannot run in stackoverflow with import statementsXanthous
While you are right that "Your index.js must look like this after the command executes." the question remains: Why does create-react-app bootstrap an application with an error in it? It's a brand new app running the latest version. Is there a reason behind the developers shipping it in a broken state?Epencephalon
S
6

As your error states, ReactDOM.render is no longer supported. So use the new createRoot.

As you can see from the code below, (which was pulled from the documentation) all you have to do is replace ReactDOM.render with createRoot.

// Before
import { render } from 'react-dom';
const container = document.getElementById('app');
render(<App tab="home" />, container);

// After
import { createRoot } from 'react-dom/client';
const container = document.getElementById('app');
const root = createRoot(container);
root.render(<App tab="home" />);
Swig answered 29/3, 2022 at 20:31 Comment(0)
G
5

In your index.js file:

import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";

Use this before React version 18

// ReactDOM.render(
//   <React.StrictMode>
//     <App />
//   </React.StrictMode>,
//   document.getElementById("root")
// );

Use this in React version 18

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App />);
Geez answered 31/3, 2022 at 9:38 Comment(2)
Why is the second part (seemingly) outcommented?Genital
With this solution I get the error: index.tsx:19 Uncaught Error: useHref() may be used only in the context of a <Router> component. Any workaround please ?Queenhood
T
4

If your application is using React-Router, then the following code will work fine:

import { createRoot } from "react-dom/client";
const container = document.getElementById("root");
const root = createRoot(container);
root.render(
  <BrowserRouter>
    <App />
  </BrowserRouter>
);

It will work perfectly (with react-router).

Tipper answered 6/4, 2022 at 8:46 Comment(2)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Chryso
Since I'm new to React, I'm not sure if this is a relevant question, but it looks like the element Id won't always be 'root'. In that case, it seems the createRoot() call would probably be something else. Is there a more general answer?Clockwork
H
3

This should do it:

import React from 'react';
import {createRoot}  from 'react-dom/client';
import App from './App';

const root = createRoot(document.getElementById("root"))
root.render
  (
    <App />
  )
Hairpin answered 31/3, 2022 at 19:54 Comment(1)
An explanation would be in order. E.g., what is the idea/gist? From the Help Center: "...always explain why the solution you're presenting is appropriate and how it works". Please respond by editing (changing) your answer, not here in comments (without "Edit:", "Update:", or similar - the answer should appear as if it was written today).Genital
G
3

It can be solved by upgrading to v14.

In an older version we experienced an issue.

Just install the latest version:

npm i @testing-library/react@latest
Gruchot answered 15/9, 2023 at 13:50 Comment(0)
S
1

In React 18. For those that are using custom Webpack configurations, follow React Refresh Webpack Plugin. They have some HMR built in.

We are supposed to use fast refresh that has been developed by the React team.

It resolved that error message for me.

Smut answered 15/8, 2022 at 18:6 Comment(0)
C
0
import React, {createRoot} from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import "./styles.css";


const root = ReactDOM.createRoot(document.getElementById("app"));
root.render( <App />);
Cryosurgery answered 4/7, 2022 at 18:20 Comment(0)
U
0

Use:

import React, { useEffect } from "react";
import { createRoot } from "react-dom/client";

const App: React.FC<{}> = () => {
  useEffect(() => {
    fetchOpenWeatherData("Toronto")
      .then((data) => console.log(data))
      .catch((err) => console.log(err));
  }, []);

  return (
    <div>
      <img src="icon.png" />
    </div>
  );
};

const rootEl = document.createElement("div");
document.body.appendChild(rootEl);
const root = createRoot(rootEl);
root.render(<App />);
Urinal answered 30/8, 2022 at 6:18 Comment(4)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Chryso
Do it actually run? Stack Snippets are not for general formatting.Genital
OK, the OP has left the building: "Last seen more than 1 year ago"Genital
Perhaps somebody else can chime in?Genital

© 2022 - 2024 — McMap. All rights reserved.