I got this error when I run this React code:
import React from 'react';
import ReactDOM from 'react-dom';
ReactDOM.render(
<div id="root">
<h1>Hello, world!</h1></div>,
document.querySelector('#root')
);
This is the error:
bundle.js:1194 Uncaught Error: _registerComponent(...): Target container is not a DOM element.(…)
To solve the "createRoot(...): Target container is not a DOM element" error, make sure that the ID you are using to select the element is the same ID that you have specified in your index. html file and place the react script below the code that declares the div element.
ReactDOM is a package that provides DOM specific methods that can be used at the top level of a web app to enable an efficient way of managing DOM elements of the web page. ReactDOM provides the developers with an API containing the following methods and a few more.
createRoot(container[, options]); Create a React root for the supplied container and return the root. The root can be used to render a React element into the DOM with render : const root = createRoot(container); root.
When you encounter an error saying 'ReactDOM' is not defined, it means that your application is can't find the variable ReactDOM because it hasn't been initialized yet. Generally, “X is not defined error” is caused by wrong import and different letter case between import and the imported variable call.
Apparently you forgot to add the element in your page that is the reason for which react does not find a container, to avoid this kind of problem you have to create a div element with identifier root or You have to change your selector.
import React from 'react';
import ReactDOM from 'react-dom';
ReactDOM.render(
<div id="root">
<h1>Hello, world!</h1></div>,
document.querySelector('body')
);
or
<div id="root"></div>
Try this:
In Html file:
<div id="root"></div>
In JS file:
ReactDOM.render(
<div>
<h1>Hello World!</h1>
</div>,
document.getElementById('root')
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With