Search code examples
reactjswebpackbabel-loader

React simple code error: Target container is not a DOM element


I am implemmenting react.js in an existing app.

I just added the webpack and a simple App component to check initially how it works, and am getting error:

Target container is not a DOM element.

Exactly it says in the console:

Error: Minified React error #200; visit https://reactjs.org/docs/error-decoder.html?invariant=200 for the full message or use the non-minified dev environment for full errors and additional helpful warnings.

which leads to the above message as error #200.

The view is just simple:

<script src="~/dist/index.js"></script>
<div id="root"></div>

and the component:

import React from 'react';
import ReactDOM from 'react-dom';

const App = () => <div>Hello world!</div>;

ReactDOM.render(<App />, document.getElementById("root"));

The webpack just simple setup:

const path = require("path");

module.exports = {
    entry: {
        index: "./app/index.js"
    },
    output: {
        path: path.resolve(__dirname, "../dist"),
        filename: "[name].js"
    },
    module: {
        rules: [
            {
                use: {
                    loader: "babel-loader"
                },
                test: /\.js$/,
                exclude: /node_modules/ //excludes node_modules folder from being transpiled by babel. We do this because it's a waste of resources to do so.
            }
        ]
    }
}

What am I missing?


Solution

  • Target container is not a DOM element.

    <script src="~/dist/index.js"></script>
    <div id="root"></div>
    

    The bundled script was run before the div you are attaching to was rendered. Simply reorder the script element after the div:

    <div id="root"></div>
    <script src="~/dist/index.js"></script>