简体   繁体   中英

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

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>

It looks like you forgot to define this id root in your html page, your html page should contain this id , put this line inside body, it will work:

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

You defined the id in a wrong place, use this part:

ReactDOM.render(
  <div>
     <h1>Hello, world!</h1>
  </div>,
  document.querySelector('#root')
);

Try this:

In Html file:

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

In JS file:

ReactDOM.render(
    <div>
        <h1>Hello World!</h1>
    </div>,
    document.getElementById('root')
);

In general it should look like this -> ReactDOM.render(Component, Container)

document.querySelector() should point to the container in your index.html as Mayank suggested in the comments. ( document.querySelector('.container') )

Please make sure to pass a react component you created like ReactDOM.render(<App />, document.querySelector('.container')

document.querySelector('root')更改为document.getElementById("#root")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM