React Uncaught Error: doelcontainer is geen DOM-element

Ik heb onlangs mijn webpack-configuratiebestand gemaakt:

const path = require("path");
const SRC_DIR = path.join(__dirname, "/client/src");
const DIST_DIR = path.join(__dirname, "/client/dist");
module.exports = {
  entry: `${SRC_DIR}/index.jsx`,
  output: {
    filename: "bundle.js",
    path: DIST_DIR
  },
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        include: SRC_DIR,
        exclude: /node_modules/,
        loader: "babel-loader",
        query: {
          presets: ["react", "es2015"]
        }
      }
    ]
  },
  mode: "development"
};

Deze werkt goed en bundelt het jsx-bestand:

import React from "react";
import ReactDOM from "react-dom";
class MainApp extends React.Component {
  render() {
    return (
      <div className="content">
        <h1>Hello World</h1>
      </div>
    );
  }
}
ReactDOM.render(<MainApp />, document.getElementById("app"));

En nu heb ik in het html-bestand het bundelbestand opgenomen met de div id-app.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>REACT TEST</title>
  <script src="./bundle.js"></script>
</head>
<body>
  <div id="app"></div>
</body>
</html>

Toen ik dit probeerde uit te voeren, leek het niet te werken en kreeg ik de foutmelding:

Uncaught Error: Target container is not a DOM element.
    at invariant (invariant.js:42)
    at legacyRenderSubtreeIntoContainer (react-dom.development.js:17116)
    at Object.render (react-dom.development.js:17195)
    at eval (index.jsx:48)
    at Object../client/src/index.jsx (bundle.js:97)
    at __webpack_require__ (bundle.js:20)
    at bundle.js:84
    at bundle.js:87
invariant   @   invariant.js:42

Wat mis ik hier? Waarom krijg ik deze foutmelding?


Antwoord 1, autoriteit 100%

Zoals jij het hebt, werkt het nog voordat je DOM hebt.

Je zou het als volgt onderaan moeten opnemen:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>REACT TEST</title>
</head>
<body>
  <div id="app"></div>
  <script src="./bundle.js"></script>
</body>
</html>

Antwoord 2, autoriteit 26%

U voegt uw React-script in vóór de initialisatie van de container. Maak het als volgt:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>REACT TEST</title>
</head>
<body>
  <div id="app"></div>
  <script src="./bundle.js"></script>
</body>
</html>

Other episodes