'Issue importing createRoot from react-dom/client

After using create-react-app and updating the index.js ReactDOM.render to React 18 I get this error: "Warning: You are importing createRoot from 'react-dom' which is not supported. You should instead import it from 'react-dom/client'".

Index.js:

import React from 'react';
import ReactDOM from 'react-dom';
import { createRoot } from 'react-dom/client';
import Switch from './components/Switch';

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


Solution 1:[1]

Recently createRoot have been moved to react-dom/client in React 18 RC (RC 1), Source

So, Now you can do this :

import * as ReactDOMClient from 'react-dom/client';
ReactDOMClient.createRoot(/*...*/);

And in your case, this should be like

import React from 'react';
import ReactDOM from 'react-dom';
import * as ReactDOMClient from 'react-dom/client';
import Switch from './components/Switch';

const root = ReactDOMClient.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <Switch />
  </React.StrictMode>
);

Motivation: There are two reasons for this change.

First, it allows components to use the isomorphic APIs such as flushSync without pulling in the client-specific entry. This means that if you server render a component that only uses flushSync on the client, the server doesn't need to pull in the client-specific code for createRoot or hydrateRoot.

Second, it creates parity with react-dom/server More Info

Solution 2:[2]

For all the typescript users, add this if you're getting the classic "no types found for this module" warning.

src/react-app-env.d.ts

declare module "react-dom/client" {
  // typing module default export as `any` will allow you to access its members without compiler warning
  var createRoot: any;
  export {createRoot};
}

Solution 3:[3]

make sure your react-dom version is "^18.0.0"

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Faisal Nazik
Solution 2 Edward Casanova
Solution 3 Monis Ansari