skip to Main Content

I am experimenting with React.

In the following script I have imported ‘createRoot’.

The browser console throws a warning:

You are importing createRoot from "react-dom" which is not supported.
You should instead import it from "react-dom/client".

However, in my script I have imported createRoot from ‘react-dom/client’.

What is going wrong here?

This is the current state of the script:

import React from 'react' ;
import * as ReactDOM from 'react-dom';
import {createRoot} from 'react-dom/client';



export default function TodoList() {

    return(
    <>
    <h1>Lets do stuff!</h1>
    </>
    )

}

const app = document.getElementById('app');
const root = ReactDOM.createRoot(app);

2

Answers


  1. You should use the createRoot, not from ReactDOM

    import * as ReactDOM from 'react-dom';
    import {createRoot} from 'react-dom/client';
    
    // X
    const root = ReactDOM.createRoot(app);  
    // V
    const root = createRoot(app);
    

    PS: See React Doc

    Login or Signup to reply.
  2. In React 18, you no longer import from react-dom directly. Instead, you import the createRoot function from react-dom/client and you create a root based on the div element with id="app" you get from the DOM. Then, you render your <App /> component (or however you named it) by calling the root.render function and passing your component (which is the root of your app).

    Your index.jsx (or index.js file) should look like this:

    import React from 'react';
    import { createRoot } from 'react-dom/client';
    import App from './App';
    
    const root = createRoot(document.getElementById('app'));
    root.render(<App />);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search