Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue importing createRoot from react-dom/client

Tags:

reactjs

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>
);
like image 258
rai. Avatar asked Sep 02 '25 10:09

rai.


2 Answers

The error message received indicates that you should be importing the createRoot method from react-dom/client instead of from react-dom.

To fix the issue, modify your import statement for createRoot to look like this :

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

So the modified code should be :

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

const root = createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <Switch />
  </React.StrictMode>
);
like image 78
Faisal Nazik Avatar answered Sep 04 '25 03:09

Faisal Nazik


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};
}
like image 24
Edward Casanova Avatar answered Sep 04 '25 01:09

Edward Casanova