Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncaught Error: _registerComponent(...): Target container is not a DOM element.(…)

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.(…)

like image 899
flower Avatar asked Jan 25 '17 09:01

flower


People also ask

How do I fix 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.

Which package provides the Dom specific method?

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.

What is ReactDOM createRoot?

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.

Why is ReactDOM undefined?

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.


2 Answers

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>
like image 152
Hajji Tarik Avatar answered Sep 30 '22 17:09

Hajji Tarik


Try this:

In Html file:

<div id="root"></div>

In JS file:

ReactDOM.render(
    <div>
        <h1>Hello World!</h1>
    </div>,
    document.getElementById('root')
);
like image 35
Duy Nguyen Avatar answered Sep 30 '22 17:09

Duy Nguyen