Search code examples
reactjsvite

Issue with React's createRoot Function


I'm encountering an issue with React's createRoot function in my project. When I attempt to use ReactDOM.createRoot(document.getElementById('root')).render(<App />);, I receive the following error in the console: Uncaught Error: createRoot(...): Target container is not a DOM element.

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

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

I have verified that the element with id="root" exists in my HTML file.


Solution

  • You just try to use the below format,

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

    refer this document link: createRoot

    Additional point: ReactDOM.render was deprecated in the ReactJS v18.0.0 (Removed: ReactDOM.render)