React App: Cannot find module 'react-dom/client' or its corresponding type declarations

12k Views Asked by At

I'm currently experiencing this error and I'm not really sure how to fix it. I've been trying to merge a project with components stored in bit.dev.

import React from 'react';
import { createRoot } from 'react-dom/client'; // Cannot find module 'react-dom/client' or its corresponding type declarations.
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { BrowserRouter } from 'react-router-dom';

import 'bootstrap/dist/css/bootstrap.min.css';

const rootElement = document.getElementById('root');
if (!rootElement) throw new Error('Failed to find the root element');
const root = createRoot(rootElement);
root.render(
  <React.StrictMode>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </React.StrictMode>
);

Here is the code. Thanks for your help!

3

There are 3 best solutions below

0
On BEST ANSWER

For anyone that might experience the same problem, the version of react bit.dev is using and the version the actual app is using are different. All I had to do was change the way the app was rendered (in this case react v17).

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { BrowserRouter } from 'react-router-dom';

import 'bootstrap/dist/css/bootstrap.min.css';

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

Try

import * as ReactDOM from 'react-dom/client';

Then ReactDOM.createRoot

1
On

After running npm install react react-dom or yarn add react react-dom as instructed here, you should then run

npm install -D @types/react-dom

or

yarn add -D @types/react-dom

This will add react-dom/client type declarations to your project and will remove the error you pointed at on line 2 of your code.