Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

You are calling ReactDOMClient.createRoot() on a container that has already been passed to createRoot() before [closed]

I'm using React 18 and using ReactDOM.render at 3 different levels. The first level is at the root level and I am clear and replaced it using the below code:

import { createRoot } from 'react-dom/client';
    
const root = createRoot(domElement);
root.render(reactElement);

For other two levels (children of root), I want to render a certain Component in a designated DOM element. If I am using:

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

const root = createRoot(childDomElement);
root.render(reactElement);

I am getting the following warning:

You are calling ReactDOMClient.createRoot() on a container that has already been passed to createRoot() before. Instead, call root.render() on the existing root instead if you want to update it.

What is the right way to render a Component in a particular DOM element?

like image 974
RahulGarg Avatar asked Sep 03 '25 09:09

RahulGarg


1 Answers

It also happen to me. For me, it because DOMContentLoaded callback triggered twice.

My fix just make sure the container rendered only once.

let container = null;

document.addEventListener('DOMContentLoaded', function(event) {
  if (!container) {
    container = document.getElementById('root1') as HTMLElement;
    const root = createRoot(container)
    root.render(
      <React.StrictMode>
        <h1>ZOO</h1>
      </React.StrictMode>
    );
  }
});
like image 173
Nadiar Syaripul Avatar answered Sep 04 '25 22:09

Nadiar Syaripul



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!