You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ReactJs报错:Target container is not a DOM element 排查求助

Fixing "Target container is not a DOM element" in React

Hey there! That error is super common when you're starting out with React—let's break down the most likely issues and how to fix them quickly:

1. Your React script is running before the DOM loads

React tries to mount your app into a DOM element that doesn't exist yet because your index.js is loading before the browser has parsed the container element.

Fixes:

  • Move your script tag to the end of the <body> in your index.html file, right before the closing </body> tag. This way, the browser loads all DOM elements first before running your React code:
    <!-- public/index.html -->
    <body>
      <div id="root"></div>
      <!-- Script goes here -->
      <script src="../src/index.js"></script>
    </body>
    
  • If you need to keep the script in the <head>, add the defer attribute to it. This tells the browser to load the script after the DOM is ready:
    <head>
      <script src="../src/index.js" defer></script>
    </head>
    

2. You've got a typo in your container element's ID

Double-check that the ID you're targeting in index.js matches exactly what's in your index.html—IDs are case-sensitive!

For example, if your HTML has:

<div id="app-container"></div>

Your React code should use the same ID:

// src/index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';

// Correct ID here
const root = ReactDOM.createRoot(document.getElementById('app-container'));
root.render(<App />);

3. You forgot to add the container element entirely

Make sure your index.html actually has a div (or any DOM element) for React to mount into. This is the most common oversight for beginners!

Add this to your public/index.html inside the <body> tag:

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

Then ensure your index.js targets this exact ID.

If none of these fix it, pop open your browser's DevTools (F12) and run document.getElementById('your-target-id') in the console—if it returns null, that confirms the element isn't available when React tries to use it.

内容的提问来源于stack exchange,提问作者user3334226

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 07:47:58