Ошибка target container is not a dom element

I just got started using React, so this is probably a very simple mistake, but here we go. My html code is very simple:

<!-- base.html -->
<html>
  <head>
    <title>Note Cards</title>
    <script src="http://<url>/react-0.11.2.js"></script>
<!--     <script src="http://<url>/JSXTransformer-0.11.2.js"></script> -->
    <script src="http://code.jquery.com/jquery-1.10.0.min.js"></script>
    {% load staticfiles %}
    <link rel="stylesheet" type="text/css" href="{% static "css/style.css" %}">
    <script src="{% static "build/react.js" %}"></script>
  </head>
  <body>
    <h1 id="content">Note Cards</h1>
    <div class="gotcha"></div>
  </body>
</html>

Note that I am using Django’s load static files here. (My JavaScript is a bit more complex, so I won’t post it all here unless someone requests it.) This is the line with the error:

React.renderComponent(
  CardBox({url: "/cards/?format=json", pollInterval: 2000}),
  document.getElementById("content")
);

After which I get the ‘target container is not a DOM element error’ yet it seems that document.getElementById(«content») is almost certainly a DOM element.

I looked at this stackoverflow post, but it didn’t seem to help in my situation.

Anyone have any idea why I’d be getting that error?

Super Jade's user avatar

Super Jade

5,3837 gold badges38 silver badges59 bronze badges

asked Oct 17, 2014 at 1:03

lnhubbell's user avatar

1

I figured it out!

After reading this blog post I realized that the placement of this line:

<script src="{% static "build/react.js" %}"></script>

was wrong. That line needs to be the last line in the <body> section, right before the </body> tag. Moving the line down solves the problem.

My explanation for this is that react was looking for the id in between the <head> tags, instead of in the <body> tags. Because of this it couldn’t find the content id, and thus it wasn’t a real DOM element.

Mahesh Pawar's user avatar

answered Oct 17, 2014 at 1:12

lnhubbell's user avatar

lnhubbelllnhubbell

3,2445 gold badges17 silver badges22 bronze badges

3

Also make sure id set in index.html is same as the one you referring to in index.js

index.html:

<body> 
    <div id="root"></div>
    <script src="/bundle.js"></script>
</body>

index.js:

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

Ghasem's user avatar

Ghasem

14.2k20 gold badges136 silver badges169 bronze badges

answered Dec 7, 2018 at 7:44

Alia Anis's user avatar

Alia AnisAlia Anis

1,31510 silver badges7 bronze badges

1

webpack solution

If you got this error while working in React with webpack and HMR.

You need to create template index.html and save it in src folder:

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

Now when we have template with id="root" we need to tell webpack to generate index.html which will mirror our index.html file.

To do that:

plugins: [
    new HtmlWebpackPlugin({
        title: "Application name",
        template: './src/index.html'
    })
],

template property will tell webpack how to build index.html file.

Kesha Antonov's user avatar

answered Aug 2, 2020 at 13:50

Predrag Davidovic's user avatar

1

Just to give an alternative solution, because it isn’t mentioned.

It’s perfectly fine to use the HTML attribute defer here. So when loading the DOM, a regular <script> will load when the DOM hits the script. But if we use defer, then the DOM and the script will load in parallel. The cool thing is the script gets evaluated in the end — when the DOM has loaded (source).

<script src="{% static "build/react.js" %}" defer></script>

answered Jan 23, 2019 at 9:10

mikemols's user avatar

mikemolsmikemols

80410 silver badges17 bronze badges

Also, the best practice of moving your <script></script> to the bottom of the html file fixes this too.

answered Feb 5, 2016 at 22:06

daniella's user avatar

danielladaniella

4037 silver badges17 bronze badges

1

For those that implemented react js in some part of the website and encounter this issue.
Just add a condition to check if the element exist on that page before you render the react component.

<div id="element"></div>

...

const someElement = document.getElementById("element")
    
if(someElement) {
  ReactDOM.render(<Yourcomponent />, someElement)
}

answered Jan 29, 2021 at 1:58

alfieindesigns's user avatar

1

I had encountered the same error with React version 16. This error comes when the Javascript that tries to render the React component is included before the static parent dom element in the html. Fix is same as the accepted answer, i.e. the JavaScript should get included only after the static parent dom element has been defined in the html.

answered Apr 9, 2019 at 10:52

Binita Bharati's user avatar

Binita BharatiBinita Bharati

5,1101 gold badge40 silver badges24 bronze badges

Also you can do something like that:

document.addEventListener("DOMContentLoaded", function(event) {
  React.renderComponent(
    CardBox({url: "/cards/?format=json", pollInterval: 2000}),
    document.getElementById("content")
  );
})

The DOMContentLoaded event fires when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.

answered May 12, 2020 at 3:51

user2226755's user avatar

user2226755user2226755

12.3k5 gold badges50 silver badges73 bronze badges

One of the case I encountered the same error in a simple project. I hope the solution helps someone.

Below code snippets are sufficient to understand the solution :

index.html

  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
  </body>

someFile.js : Notice the line const portalElement = document.getElementById(«overlays»); below :

const portalElement = document.getElementById("overlays");

const Modal = (props) => {
  return (
    <Fragment>
            {ReactDOM.createPortal(<Backdrop />, portalElement)}
            
      {ReactDOM.createPortal(
        <ModalOverlay>{props.children}</ModalOverlay>,
        portalElement
      )}
          
    </Fragment>
  );
};

I didn’t have any element with id = «overlays» in my index.html file, so the highlighted line above was outputting null and so React wasn’t able to find inside which element it should create the portal i.e {ReactDOM.createPortal(<Backdrop />, portalElement)} so I got below error

enter image description here

I added the div in index.html file and the error was gone.

 <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="overlays"></div>
    <div id="root"></div>
  </body>

answered Jun 28, 2021 at 14:14

utkarsh-k's user avatar

utkarsh-kutkarsh-k

7227 silver badges16 bronze badges

I got the same error i created the app with create-react-app but in /public/index.html also added matrialize script but there was to connection with «root» so i added

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

just before

<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/ materialize.min.js"></script>

And it worked for me .

answered Aug 2, 2020 at 6:37

1

Target container is not a DOM element.

I achieved this error with a simple starter app also.

// index.js

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

Solution:

Syntax errors can cause this error. I checked my syntax and wrapped my <App /> properly.

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

answered Aug 26, 2021 at 6:10

Super Jade's user avatar

Super JadeSuper Jade

5,3837 gold badges38 silver badges59 bronze badges

In my case, I forget to add this line to the index.js file

document.getElementById('root')

and I forget to import react-dom import ReactDOM from 'react-dom'; so you can use ReactDOM later in the same file

Hope this will be helpful for you

answered Nov 8, 2022 at 15:06

hadeel salah's user avatar

The target container is not a DOM element test and is a typical React error when developers introduce the build script before the root element. But, unfortunately, the codesandbox target container is not a DOM element bug that can affect your React script if it includes an incorrect configuring web pack file, which confuses your system.target container is not a dom element

Henceforth, we wrote this profound target container is not a DOM element react testing-library article to help developers face this obstacle in their programming experience.

This is the most sophisticated guide because it recreates this uncaught error, provides debugging techniques, and helps developers locate the possible culprits, so keep reading for more.

Contents

  • Why the System Launches the Target Container Is Not a DOM Element Bug?
    • – Using React Load Static Files
    • – The Build Script Exists Before the Root Element
    • – The File Exists in a Public Directory
  • Target Container Is Not a DOM Element: 2 Profound Solutions
    • – Using Identical Unique Identifiers Specified in the Index
  • Conclusion

Why the System Launches the Target Container Is Not a DOM Element Bug?

Your system launches the target container is not a DOM element. React jest error when the build script appears before the room element. Moreover, our developers confirmed an identical error when your document contains an incorrect configuring web pack file, confusing your system due to a lack of fair values.

Unfortunately, this mistake will affect straightforward and complex syntaxes unless developers introduce all build scripts before the closing body tag. As a result, our experts provide several invalid scripts and syntaxes that recreate this mistake to help you locate the culprit and pinpoint the incorrect element.

Although the target container is not a DOM element react 18 error does not have a challenging structure, it can obliterate your document and halt further operations. However, another possible cause for the target container is not a DOM element. nextJS mistake exists, as explained below.

Namely, several developers reported this error when they passed an invalid ID of the HTML div element to the getElementByID method. Although implementing this method in your script should not cause the target container is not a DOM element. storybook bug can appear if your unique identification is invalid or has incorrect paths.

But, as explained before, learning about the syntaxes that launch the unmountcomponentatnode target container is not a DOM element error is essential when pinpointing the possible cause.

– Using React Load Static Files

Experiencing this bug with short scripts discourages less experienced developers because they believe everything is fine with the code. Unfortunately, this is not the case even if users have double-checked all elements and commands.

As a result, we will show you a simple HTML code that introduces a React load static file. Readers can confirm the HTML script only has simple elements and tags and a few attributes inside the opening tags.

The following example provides the HTML code:

<!– base.html –>

<html>

<head>

<title> Note Cards </title>

<script src=”http://<url> /react-0.11.3.js”> </script>

<!– <script src=”http://<url> /JSXTransformer-0.11.3.js”> </script> –>

<script src=”http://code.jquery.com/jquery-1.10.2.min.js”> </script>

{% load staticfiles %}

<link rel=”stylesheet” type=”text/css” href=”{% static “css/style.css” %}”>

<script src=”{% static “build/react.js” %}”> </script>

</head>

<body>

<h1 id=”content”> Note Cards </h1>

<div class=”confirmed”> </div>

</body>

</html>

This example confirms the HTML syntax is correct and no element launches a mistake. However, JavaScript is more complex because it includes more commands and functions, and the build script exists before the root element. Hence, the system launches this mistake that provides for other indicators and locations.

Readers can learn more about the exception message in the following example:

React.renderComponent(

CardBox ({url: “/cards/?format=json”, pollInterval: 2022}),

document.getElementById (“content”)

);

Attempting to debug this bug without reading this guide will lead you nowhere because the debugging principles follow a specific structure. However, our experts will provide other instances where developers might experience this mistake.

– The Build Script Exists Before the Root Element

Our experts confirmed that the lack of proper build script location is this error’s definitive cause. So, less skillful programmers usually write this script before the root element, which confuses the system because it cannot render the functions correctly.Target Container Is Not a DOM Element Causes

As a result, it launches the error, discouraging users because they cannot fix it. Luckily, you are at the right place.

But first, let us learn about the next example that recreates this bug:

<!DOCTYPE html>

<html lang=”en”>

<head>

<meta charset=”utf-8″ />

<link rel=”shortcut icon” href=”/favicon.ico” />

<meta name=”viewport” content=”width=device-width, initial-scale=1″ />

<meta name=”theme-color” content=”#0A00A0″ />

<link rel=”manifest” href=”/manifest.json” />

<title> Error Message </title>

<link href=”/static/css/2.1026416.chunk.css” rel=”stylesheet” />

<link href=”/static/css/main.1b26738.chunk.css” rel=”stylesheet” />

<script src=”/static/js/2.726e346a.chunk.js”> </script>

<script src=”/static/js/main.119c9f15.chunk.js”> </script>

</head>

<body>

<noscript> Developers must enable JavaScript to run this app. </noscript>

<div id=”root”> </div>

</body>

</html>

Programmers cannot use this HTML index structure because it loads the scripts before the root element and tags. Fortunately, debugging this error is straightforward, as you will soon learn.

Now, let us discover another instance where developers experience this annoying exception in their React projects and HTML documents by opening the public directory.

– The File Exists in a Public Directory

Developers are guaranteed to face this mistake when writing the index HTML document in a public directory of the React project. Unfortunately, this is invalid and launches an error because the unique identifiers in both documents differ.

Our team believes beginners make this error because they use template files on the React 18 documentation page while launching the project with a creative application.

The following code recreates this annoying exception:

import React from “react”;

import { createRoot } from “react-dom/client”;

import App from “./App”;

const rootElement = document.getElementById(“app”);

//id is given as app

const root = createRoot(rootElement);

root.render(

<React.StrictMode>

<App />

</React.StrictMode>

);

We will now provide the general index HTML file with a unique identifier that acts as a root. So, the following example completes this syntax:

<body>

<noscript> You must enable JavaScript to run this app. </noscript>

<div id=”root”></div> <!– id is given as root –>

</body>

After learning about the invalid scripts, it is time to discover the debugging principles.

Target Container Is Not a DOM Element: 2 Profound Solutions

Writing and loading the scripts after the root element are the best solutions to this target container is not a DOM element error. So, developers and programmers must first locate the main feature, delete the scripts, and include them after the root closing tag.



We will use the same example, including correct values and element positions. Read the following example to fix your script:

<!DOCTYPE html>

<html lang=”en”>

<head>

<meta charset=”utf-8″ />

<link rel=”shortcut icon” href=”/favicon.ico” />

<meta name=”viewport” content=”width=device-width, initial-scale=1″ />

<meta name=”theme-color” content=”#0A00A0″ />

<link rel=”manifest” href=”/manifest.json” />

<title> Error Solution </title>

<link href=”/static/css/2.102366419.chunk.css” rel=”stylesheet” />

<link href=”/static/css/main.1b12638.chunk.css” rel=”stylesheet” />

</head>

<body>

<noscript> You must enable JavaScript to run this app. </noscript>

<div id=”root”> </div>

<script src=”/static/js/2.5136e345a.chunk.js”> </script>

<script src=”/static/js/main.119c9f54.chunk.js”> </script>

</body>

</html>

As you can tell, although a few minor differences exist, we have kept the script the same. Still, it is correct and will not launch a mistake.

Fortunately, other advanced debugging methods and principles help developers clear their scripts.

– Using Identical Unique Identifiers Specified in the Index

Writing identical unique identifiers specified in the HTML index file is another full-proof debugging principle that clears your document. For instance, programmers must ensure the ID that selects the element is the same ID that they have specified in the HTML file and place the script below.Using Identical Unique Identifiers Specified in the Index

We declared the div element with identical unique identifiers in this example:

<!DOCTYPE html>

<html lang=”en”>

<body>

<!– must match with index.js –>

<div id=”root”> </div>

</body>

</html>

So, programmers must use the root identifier when selecting this element in the index JavaScript. Readers can learn how to do this in the following example:

import {StrictMode} from ‘react’;

import {createRoot} from ‘react-dom/client’;

import App from ‘./App’;

// correct ID passed

const rootElement = document.getElementById(‘root’);

const root = createRoot(rootElement);

root.render(

<StrictMode>

<App />

</StrictMode>,

);

This script completes our comprehensive debugging guide.

Conclusion

Our team confirmed passing an incorrect unique identifier and misplacing the React script commands are the two culprits for this mistake. Luckily, this guide explained many essential points covered in the following bullet list, so let us remember the details:

  • This mistake affects long and short HTML and JavaScript documents
  • Although the invalid exception is straightforward, pinpointing the error is sometimes challenging
  • This article recreates the bug using several standard examples
  • Following the debugging principles from this article will help you enable the script without further complications

We assure beginners and novice developers to clear their documents from this bug because this guide has all they need. So, discover the elements, paste them into your file, and complete your project.

  • Author
  • Recent Posts

Position is Everything

Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL. Meet The Team

Position is Everything

The error «createRoot() Target container is not a DOM element» is mostly caused by two reasons:

error message
  1. When we pass the wrong id of the HTML div tag to the «document.getElementById()» method.
  2. The React script was placed before the div tag with id in the index.html file.

1. Wrong id in document.getElementById()

The following code is a representation of how this error could occur.

import React from "react";
import { createRoot } from "react-dom/client";
import App from "./App";

const rootElement = document.getElementById("app"); 👈 
//id is given as app

const root = createRoot(rootElement);
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);
src/index.js
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>  👈 <!-- id is given as root -->
  </body>
public/index.html

The above codes are for the root index file for a React project and the «index.html» file that exist in the «public» directory. Notice how the ids are different in these two files. This is the most common mistake that could lead to this error. Mostly this happens because of using template files on the React 18 documentation page itself while initializing the project with «create-react-app».

Solution

You need to make sure you are using the same id in both the «index.js» and «index.html» files mentioned above

2. React script file is written before the div tag with id

If you have loaded yourReact script externally to an existing website, there might be a chance that you defined your script before the div tag with id. This is a less occurring incident since it is common practice to put javascript at the end of the «body» tag in any HTML file. However, I included this as there might be a chance you could have made this mistake by accident.

If the «index.html» file in the public directory has its div tag with id placed after the React script like this:

<!DOCTYPE html>
<html lang="en">
<body>
    <script src="https://unpkg.com/react@18/umd/react.development.js" crossorigin></script>
    <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js" crossorigin></script>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
</body>
</html>
index.html

Solution

Place the script at the bottom of the index.html file. And also note that it is common practice to call the scripts at the end of the HTML file by default. This ensures that all the components the script interacts with are already initialized and won’t cause an error.

Conclusion

Passing the wrong id and wrong placement of the React script are the most common occurrence of this error. This doesn’t mean that these are the only two scenarios. There are other implementation-depended occurrences of this error. For example, if you are using the HTML Webpack plugin and misconfigured the config file, this error could be triggered.

Another issue that is commonly faced by transitioning to React 18 is «ReactDOM.render is no longer supported in React 18. Use createRoot instead». Check out my below article for the solution to it.

Solved — ReactDOM.render is no longer supported in React 18. Use createRoot instead.

“ReactDOM.render” method which is by default used in create-react-app or other template files is deprecated in React 18. Check out the new implementation of the index.js file.

I hope I was helpful to most of you who faced this issue. If interested, check out the featured article on my blog. Thank you.

Subscribe to Sharooq

Join the growing community of friendly readers through my monthly newsletter.

Email

Great!

Check your inbox and click the link to confirm your subscription

.

Please enter a valid email address

!

Answer by Roman Henderson

App.jsx is supposed to export the App class and do nothing more, render should be called elsewhere.,In my case, I was exporting an object within my index.js where I was also calling ReactDOM.render. I removed this export and voila! ,A small note before you go. Here is how to use the default and the non-default exports.

As I see, this error arises in many cases and requires different approaches to solve it. My scenario is not the same as the example above, I use redux & router, although I was struggling with the same error. What helped me to solve this problem is to change index.js from:

ReactDOM.render(
  <Provider store={store}>
    <AppRouter />
  </Provider>,
  document.getElementById("root")
);
registerServiceWorker();

to:

ReactDOM.render(
    (<Provider store={store}>
        <AppRouter/>
    </Provider>),
     document.getElementById('root') || document.createElement('div') // for testing purposes
);
registerServiceWorker();

Answer by Kingston Price

For anyone else that was combing through the internet like I’ve been — looking for a solution to this when testing with Jest — I will back up the answer by @biphobe by saying Jest will cause this error to occur when you export something inside the same file that is calling ReactDOM.render. ,As I see, this error arises in many cases and requires different approaches to solve it. My scenario is not the same as the example above, I use redux & router, although I was struggling with the same error. What helped me to solve this problem is to change index.js from:,In my case, I was exporting an object within my index.js where I was also calling ReactDOM.render. I removed this export and voila!

As I see, this error arises in many cases and requires different approaches to solve it. My scenario is not the same as the example above, I use redux & router, although I was struggling with the same error. What helped me to solve this problem is to change index.js from:

ReactDOM.render(
  <Provider store={store}>
    <AppRouter />
  </Provider>,
  document.getElementById("root")
);
registerServiceWorker();

to:

ReactDOM.render(
    (<Provider store={store}>
        <AppRouter/>
    </Provider>),
     document.getElementById('root') || document.createElement('div') // for testing purposes
);
registerServiceWorker();

Answer by Ariana Velasquez

The initial code that didn’t work when testing React looked like this.,
default export store; is used with import store from «./store»;
,
export const store = … is used with import { store } from «./store»;

The initial code that didn’t work when testing React looked like this.

// index.tsx

import * as React from "react";
import { render } from "react-dom";
import { Provider } from "react-redux";
import { applyMiddleware, compose, createStore } from "redux";
import App from "./components/App";
import { rootReducer } from "./store/reducers";
import { initialState } from "./store/state";

const middlewares = [];

export const store = createStore(
    rootReducer,
    initialState,
    compose(applyMiddleware(...middlewares)),
);

render(
    <Provider store={store}>
        <App />
    </Provider>,
    document.getElementById("root"),
);

Separate the Redux store logic into a new file named store.ts, then create a default export (to be used by index.tsx, i.e., the React application) and a non-default export with export const store (to be used from non-React classes), as follows.

// store.ts

import { applyMiddleware, compose, createStore } from "redux";
import logger from "redux-logger";
import { rootReducer } from "./store/reducers";
import { initialState } from "./store/state";

const middlewares = [];

export const store = createStore(
    rootReducer,
    initialState,
    compose(applyMiddleware(...middlewares)),
);

export default store;
// updated index.tsx

import * as React from "react";
import { render } from "react-dom";
import { Provider } from "react-redux";
import App from "./components/App";
import store from "./store";

render(
    <Provider store={store}>
        <App />
    </Provider>,
    document.getElementById("root"),
);
// MyClass.ts

import { store } from "./store"; // store.ts

export default class MyClass {
  handleClick() {
    store.dispatch({ ...new SomeAction() });
  }
}

Answer by Ezequiel Rasmussen

I’m attempting to test a React component with Jest/Enzyme while using Webpack.,Invariant Violation: _registerComponent(…): Target container is not a DOM element.,https://nono.ma/says/solved-invariant-violation-target-container-is-not-a-dom-element

I have a very simple test @

import React from 'react';
import { shallow } from 'enzyme';

import App from './App';

it('App', () => {
  const app = shallow(<App />);
  expect(1).toEqual(1);
});

The relative component it’s picking up is :

import React, { Component } from 'react';
import { render } from 'react-dom';

// import './styles/normalize.css';

class App extends Component {
  render() {
    return (
      <div>app</div>
    );
  }
}

render(<App />, document.getElementById('app'));

For those interested (Webpack code):

module.exports = {
  entry: './src/App',
  output: {
    filename: 'bundle.js',
    path: './dist'
  },
  module: {
    loaders: [
      {
        test: /.js?$/,
        exclude: /node_modules/,
        loader: 'babel',
        query: {
          presets: ['react', 'es2015']
        }
      },
      {
        test: /.css$/,
        loader: 'style!css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]'
      },
      {
        test: /.scss$/,
        loader: 'style!css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]!sass'
      }
    ]
  }
}

And my package.json:

{
  "name": "tic-tac-dux",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "dev": "webpack-dev-server --devtool eval --progress --colors --inline --hot --content-base dist/",
    "test": "jest"
  },
  "jest": {
    "moduleNameMapper": {
      "^.+.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
      "^.+.(css|sass)$": "<rootDir>/__mocks__/styleMock.js"
    }
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "babel-core": "^6.17.0",
    "babel-jest": "^16.0.0",
    "babel-loader": "^6.2.5",
    "babel-polyfill": "^6.16.0",
    "babel-preset-es2015": "^6.16.0",
    "babel-preset-react": "^6.16.0",
    "css-loader": "^0.25.0",
    "enzyme": "^2.4.1",
    "jest": "^16.0.1",
    "jest-cli": "^16.0.1",
    "node-sass": "^3.10.1",
    "react-addons-test-utils": "^15.3.2",
    "react-dom": "^15.3.2",
    "sass-loader": "^4.0.2",
    "style-loader": "^0.13.1",
    "webpack": "^1.13.2",
    "webpack-dev-server": "^1.16.2"
  },
  "dependencies": {
    "react": "^15.3.2",
    "react-dom": "^15.3.2"
  }
}

Oh, and if anyone is going to say that the div element isn’t being loaded before the script, here’s my index.html:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>App</title>
  </head>
  <body>
    <div id="app"></div>
    <script src="/bundle.js"></script>
  </body>
</html>

Answer by Hendrix Morris

React throws the error, target container is not a dom element, when we include the build script before the root element. The solution is to always include the build scripts before body closing tag </body>.,This file will create target container is not a dom element error because our scripts are loaded before out root element.,I am Akash Mittal, an overall computer scientist. If you want to guest post, need help in your projects, want to advertise, Feel free to contact me at [email protected]

Suppose the html structure of index.html is –

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="shortcut icon" href="/favicon.ico" />
    <meta name="viewport" content="width=device-width,initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <link rel="manifest" href="/manifest.json" />
    <title>Error Template</title>
    <link href="/static/css/2.10306419.chunk.css" rel="stylesheet" />
    <link href="/static/css/main.1b589238.chunk.css" rel="stylesheet" />
    <script src="/static/js/2.537e346a.chunk.js"></script>
    <script src="/static/js/main.119c9f53.chunk.js"></script>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
  </body>
</html>

The correct way is –

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="shortcut icon" href="/favicon.ico" />
    <meta name="viewport" content="width=device-width,initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <link rel="manifest" href="/manifest.json" />
    <title>Error Template</title>
    <link href="/static/css/2.10306419.chunk.css" rel="stylesheet" />
    <link href="/static/css/main.1b589238.chunk.css" rel="stylesheet" />
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
    <script src="/static/js/2.537e346a.chunk.js"></script>
    <script src="/static/js/main.119c9f53.chunk.js"></script>
  </body>
</html>

Now you can use it in your App.js or index.js files –

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

Answer by Dillon Kennedy


Answer by Opal Reid

React testing error: Target container is not a DOM element
,
React testing error: Target container is not a DOM element ,

TypeError: is not a function — in simple react component


Answer by Madeline Dominguez

I know that the problem becomes from the last part of code (ReactDOM.render) but i don’t know with certainty what is it.,All Telerik .NET tools and Kendo UI JavaScript components in one package. Now enhanced with:,I am a beginner with js and react and i try in my environment to recreate a chart.

I have everything I need (package, react, etc) but I can’t make it work the example code.


Answer by Keenan Mercado

note: in old tutorials you may see import of react-testing-library/cleanup this is no longer required as the beforeEach and afterEach are automatically registered now,when using react-testing-library we can start by importing render and use it instead of ReactDOM,Using react-dom we have code like this to test a react component

Using react-dom we have code like this to test a react component

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

let container = null;
beforeEach(() => {
  // setup a DOM element as a render target
  container = document.createElement("div");
  document.body.appendChild(container);
});

afterEach(() => {
  // cleanup on exiting
  ReactDOM.unmountComponentAtNode(container);
  container.remove();
  container = null;
});

/* ######## setup code above ######## */

function App() {
  return (
    <div>
      <h1>Hello!</h1>
    </div>
  );
}

test("render app", () => {
  ReactDOM.render(<App />, container);
  expect(document.querySelector("h1").textContent).toBe("Hello!");
});

when using react-testing-library we can start by importing render and use it instead of ReactDOM

  import React from 'react'
  import ReactDOM from 'react-dom'
+ import { render } from '@testing-library/react'

  let container = null
  beforeEach(() => {
    // setup a DOM element as a render target
    container = document.createElement('div')
    document.body.appendChild(container)
  })

  afterEach(() => {
    // cleanup on exiting
    ReactDOM.unmountComponentAtNode(container)
    container.remove()
    container = null
  })

  /* ######## setup code above ######## */

  function App() {
    return (
      <div>
        <h1>Hello!</h1>
      </div>
    )
  }

  test('render app', () => {
-   ReactDOM.render(<App />, container)
+   render(<App />)
    expect(document.querySelector('h1').textContent).toBe('Hello!')
  })
  import React from 'react'
- import ReactDOM from 'react-dom'
  import { render } from '@testing-library/react'
-
- let container = null
- beforeEach(() => {
-   // setup a DOM element as a render target
-   container = document.createElement('div')
-   document.body.appendChild(container)
- })
-
- afterEach(() => {
-   // cleanup on exiting
-   ReactDOM.unmountComponentAtNode(container)
-   container.remove()
-   container = null
- })
-
- /* ######## setup code above ######## */

  function App() {
    return (
      <div>
        <h1>Hello!</h1>
      </div>
    )
  }

  test('render app', () => {
    render(<App />)
    expect(document.querySelector('h1').textContent).toBe('Hello!')
  })

Comments

@pelotom

Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL. Meet The Team

Position is Everything

The error «createRoot() Target container is not a DOM element» is mostly caused by two reasons:

error message
  1. When we pass the wrong id of the HTML div tag to the «document.getElementById()» method.
  2. The React script was placed before the div tag with id in the index.html file.

1. Wrong id in document.getElementById()

The following code is a representation of how this error could occur.

import React from "react";
import { createRoot } from "react-dom/client";
import App from "./App";

const rootElement = document.getElementById("app"); 👈 
//id is given as app

const root = createRoot(rootElement);
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);
src/index.js
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>  👈 <!-- id is given as root -->
  </body>
public/index.html

The above codes are for the root index file for a React project and the «index.html» file that exist in the «public» directory. Notice how the ids are different in these two files. This is the most common mistake that could lead to this error. Mostly this happens because of using template files on the React 18 documentation page itself while initializing the project with «create-react-app».

Solution

You need to make sure you are using the same id in both the «index.js» and «index.html» files mentioned above

2. React script file is written before the div tag with id

If you have loaded yourReact script externally to an existing website, there might be a chance that you defined your script before the div tag with id. This is a less occurring incident since it is common practice to put javascript at the end of the «body» tag in any HTML file. However, I included this as there might be a chance you could have made this mistake by accident.

If the «index.html» file in the public directory has its div tag with id placed after the React script like this:

<!DOCTYPE html>
<html lang="en">
<body>
    <script src="https://unpkg.com/react@18/umd/react.development.js" crossorigin></script>
    <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js" crossorigin></script>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
</body>
</html>
index.html

Solution

Place the script at the bottom of the index.html file. And also note that it is common practice to call the scripts at the end of the HTML file by default. This ensures that all the components the script interacts with are already initialized and won’t cause an error.

Conclusion

Passing the wrong id and wrong placement of the React script are the most common occurrence of this error. This doesn’t mean that these are the only two scenarios. There are other implementation-depended occurrences of this error. For example, if you are using the HTML Webpack plugin and misconfigured the config file, this error could be triggered.

Another issue that is commonly faced by transitioning to React 18 is «ReactDOM.render is no longer supported in React 18. Use createRoot instead». Check out my below article for the solution to it.

Solved — ReactDOM.render is no longer supported in React 18. Use createRoot instead.

“ReactDOM.render” method which is by default used in create-react-app or other template files is deprecated in React 18. Check out the new implementation of the index.js file.

I hope I was helpful to most of you who faced this issue. If interested, check out the featured article on my blog. Thank you.

Subscribe to Sharooq

Join the growing community of friendly readers through my monthly newsletter.

Email

Great!

Check your inbox and click the link to confirm your subscription

.

Please enter a valid email address

!

Answer by Roman Henderson

App.jsx is supposed to export the App class and do nothing more, render should be called elsewhere.,In my case, I was exporting an object within my index.js where I was also calling ReactDOM.render. I removed this export and voila! ,A small note before you go. Here is how to use the default and the non-default exports.

As I see, this error arises in many cases and requires different approaches to solve it. My scenario is not the same as the example above, I use redux & router, although I was struggling with the same error. What helped me to solve this problem is to change index.js from:

ReactDOM.render(
  <Provider store={store}>
    <AppRouter />
  </Provider>,
  document.getElementById("root")
);
registerServiceWorker();

to:

ReactDOM.render(
    (<Provider store={store}>
        <AppRouter/>
    </Provider>),
     document.getElementById('root') || document.createElement('div') // for testing purposes
);
registerServiceWorker();

Answer by Kingston Price

For anyone else that was combing through the internet like I’ve been — looking for a solution to this when testing with Jest — I will back up the answer by @biphobe by saying Jest will cause this error to occur when you export something inside the same file that is calling ReactDOM.render. ,As I see, this error arises in many cases and requires different approaches to solve it. My scenario is not the same as the example above, I use redux & router, although I was struggling with the same error. What helped me to solve this problem is to change index.js from:,In my case, I was exporting an object within my index.js where I was also calling ReactDOM.render. I removed this export and voila!

As I see, this error arises in many cases and requires different approaches to solve it. My scenario is not the same as the example above, I use redux & router, although I was struggling with the same error. What helped me to solve this problem is to change index.js from:

ReactDOM.render(
  <Provider store={store}>
    <AppRouter />
  </Provider>,
  document.getElementById("root")
);
registerServiceWorker();

to:

ReactDOM.render(
    (<Provider store={store}>
        <AppRouter/>
    </Provider>),
     document.getElementById('root') || document.createElement('div') // for testing purposes
);
registerServiceWorker();

Answer by Ariana Velasquez

The initial code that didn’t work when testing React looked like this.,
default export store; is used with import store from «./store»;
,
export const store = … is used with import { store } from «./store»;

The initial code that didn’t work when testing React looked like this.

// index.tsx

import * as React from "react";
import { render } from "react-dom";
import { Provider } from "react-redux";
import { applyMiddleware, compose, createStore } from "redux";
import App from "./components/App";
import { rootReducer } from "./store/reducers";
import { initialState } from "./store/state";

const middlewares = [];

export const store = createStore(
    rootReducer,
    initialState,
    compose(applyMiddleware(...middlewares)),
);

render(
    <Provider store={store}>
        <App />
    </Provider>,
    document.getElementById("root"),
);

Separate the Redux store logic into a new file named store.ts, then create a default export (to be used by index.tsx, i.e., the React application) and a non-default export with export const store (to be used from non-React classes), as follows.

// store.ts

import { applyMiddleware, compose, createStore } from "redux";
import logger from "redux-logger";
import { rootReducer } from "./store/reducers";
import { initialState } from "./store/state";

const middlewares = [];

export const store = createStore(
    rootReducer,
    initialState,
    compose(applyMiddleware(...middlewares)),
);

export default store;
// updated index.tsx

import * as React from "react";
import { render } from "react-dom";
import { Provider } from "react-redux";
import App from "./components/App";
import store from "./store";

render(
    <Provider store={store}>
        <App />
    </Provider>,
    document.getElementById("root"),
);
// MyClass.ts

import { store } from "./store"; // store.ts

export default class MyClass {
  handleClick() {
    store.dispatch({ ...new SomeAction() });
  }
}

Answer by Ezequiel Rasmussen

I’m attempting to test a React component with Jest/Enzyme while using Webpack.,Invariant Violation: _registerComponent(…): Target container is not a DOM element.,https://nono.ma/says/solved-invariant-violation-target-container-is-not-a-dom-element

I have a very simple test @

import React from 'react';
import { shallow } from 'enzyme';

import App from './App';

it('App', () => {
  const app = shallow(<App />);
  expect(1).toEqual(1);
});

The relative component it’s picking up is :

import React, { Component } from 'react';
import { render } from 'react-dom';

// import './styles/normalize.css';

class App extends Component {
  render() {
    return (
      <div>app</div>
    );
  }
}

render(<App />, document.getElementById('app'));

For those interested (Webpack code):

module.exports = {
  entry: './src/App',
  output: {
    filename: 'bundle.js',
    path: './dist'
  },
  module: {
    loaders: [
      {
        test: /.js?$/,
        exclude: /node_modules/,
        loader: 'babel',
        query: {
          presets: ['react', 'es2015']
        }
      },
      {
        test: /.css$/,
        loader: 'style!css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]'
      },
      {
        test: /.scss$/,
        loader: 'style!css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]!sass'
      }
    ]
  }
}

And my package.json:

{
  "name": "tic-tac-dux",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "dev": "webpack-dev-server --devtool eval --progress --colors --inline --hot --content-base dist/",
    "test": "jest"
  },
  "jest": {
    "moduleNameMapper": {
      "^.+.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
      "^.+.(css|sass)$": "<rootDir>/__mocks__/styleMock.js"
    }
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "babel-core": "^6.17.0",
    "babel-jest": "^16.0.0",
    "babel-loader": "^6.2.5",
    "babel-polyfill": "^6.16.0",
    "babel-preset-es2015": "^6.16.0",
    "babel-preset-react": "^6.16.0",
    "css-loader": "^0.25.0",
    "enzyme": "^2.4.1",
    "jest": "^16.0.1",
    "jest-cli": "^16.0.1",
    "node-sass": "^3.10.1",
    "react-addons-test-utils": "^15.3.2",
    "react-dom": "^15.3.2",
    "sass-loader": "^4.0.2",
    "style-loader": "^0.13.1",
    "webpack": "^1.13.2",
    "webpack-dev-server": "^1.16.2"
  },
  "dependencies": {
    "react": "^15.3.2",
    "react-dom": "^15.3.2"
  }
}

Oh, and if anyone is going to say that the div element isn’t being loaded before the script, here’s my index.html:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>App</title>
  </head>
  <body>
    <div id="app"></div>
    <script src="/bundle.js"></script>
  </body>
</html>

Answer by Hendrix Morris

React throws the error, target container is not a dom element, when we include the build script before the root element. The solution is to always include the build scripts before body closing tag </body>.,This file will create target container is not a dom element error because our scripts are loaded before out root element.,I am Akash Mittal, an overall computer scientist. If you want to guest post, need help in your projects, want to advertise, Feel free to contact me at [email protected]

Suppose the html structure of index.html is –

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="shortcut icon" href="/favicon.ico" />
    <meta name="viewport" content="width=device-width,initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <link rel="manifest" href="/manifest.json" />
    <title>Error Template</title>
    <link href="/static/css/2.10306419.chunk.css" rel="stylesheet" />
    <link href="/static/css/main.1b589238.chunk.css" rel="stylesheet" />
    <script src="/static/js/2.537e346a.chunk.js"></script>
    <script src="/static/js/main.119c9f53.chunk.js"></script>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
  </body>
</html>

The correct way is –

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="shortcut icon" href="/favicon.ico" />
    <meta name="viewport" content="width=device-width,initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <link rel="manifest" href="/manifest.json" />
    <title>Error Template</title>
    <link href="/static/css/2.10306419.chunk.css" rel="stylesheet" />
    <link href="/static/css/main.1b589238.chunk.css" rel="stylesheet" />
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
    <script src="/static/js/2.537e346a.chunk.js"></script>
    <script src="/static/js/main.119c9f53.chunk.js"></script>
  </body>
</html>

Now you can use it in your App.js or index.js files –

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

Answer by Dillon Kennedy


Answer by Opal Reid

React testing error: Target container is not a DOM element
,
React testing error: Target container is not a DOM element ,

TypeError: is not a function — in simple react component


Answer by Madeline Dominguez

I know that the problem becomes from the last part of code (ReactDOM.render) but i don’t know with certainty what is it.,All Telerik .NET tools and Kendo UI JavaScript components in one package. Now enhanced with:,I am a beginner with js and react and i try in my environment to recreate a chart.

I have everything I need (package, react, etc) but I can’t make it work the example code.


Answer by Keenan Mercado

note: in old tutorials you may see import of react-testing-library/cleanup this is no longer required as the beforeEach and afterEach are automatically registered now,when using react-testing-library we can start by importing render and use it instead of ReactDOM,Using react-dom we have code like this to test a react component

Using react-dom we have code like this to test a react component

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

let container = null;
beforeEach(() => {
  // setup a DOM element as a render target
  container = document.createElement("div");
  document.body.appendChild(container);
});

afterEach(() => {
  // cleanup on exiting
  ReactDOM.unmountComponentAtNode(container);
  container.remove();
  container = null;
});

/* ######## setup code above ######## */

function App() {
  return (
    <div>
      <h1>Hello!</h1>
    </div>
  );
}

test("render app", () => {
  ReactDOM.render(<App />, container);
  expect(document.querySelector("h1").textContent).toBe("Hello!");
});

when using react-testing-library we can start by importing render and use it instead of ReactDOM

  import React from 'react'
  import ReactDOM from 'react-dom'
+ import { render } from '@testing-library/react'

  let container = null
  beforeEach(() => {
    // setup a DOM element as a render target
    container = document.createElement('div')
    document.body.appendChild(container)
  })

  afterEach(() => {
    // cleanup on exiting
    ReactDOM.unmountComponentAtNode(container)
    container.remove()
    container = null
  })

  /* ######## setup code above ######## */

  function App() {
    return (
      <div>
        <h1>Hello!</h1>
      </div>
    )
  }

  test('render app', () => {
-   ReactDOM.render(<App />, container)
+   render(<App />)
    expect(document.querySelector('h1').textContent).toBe('Hello!')
  })
  import React from 'react'
- import ReactDOM from 'react-dom'
  import { render } from '@testing-library/react'
-
- let container = null
- beforeEach(() => {
-   // setup a DOM element as a render target
-   container = document.createElement('div')
-   document.body.appendChild(container)
- })
-
- afterEach(() => {
-   // cleanup on exiting
-   ReactDOM.unmountComponentAtNode(container)
-   container.remove()
-   container = null
- })
-
- /* ######## setup code above ######## */

  function App() {
    return (
      <div>
        <h1>Hello!</h1>
      </div>
    )
  }

  test('render app', () => {
    render(<App />)
    expect(document.querySelector('h1').textContent).toBe('Hello!')
  })

Comments

tgandrews

added a commit
to ONSdigital/eq-author
that referenced
this issue

Oct 8, 2018

@tgandrews

As part of an unintentional bump of the storybook version in
e8f9c1d it would no longer run
correctly.

The issue was already reported and relates to our webpack config
derived from CRA. storybookjs/storybook#2615

tgandrews

added a commit
to ONSdigital/eq-author
that referenced
this issue

Oct 9, 2018

@tgandrews

As part of an unintentional bump of the storybook version in
e8f9c1d it would no longer run
correctly.

The issue was already reported and relates to our webpack config
derived from CRA. storybookjs/storybook#2615

tgandrews

added a commit
to ONSdigital/eq-author
that referenced
this issue

Oct 10, 2018

@tgandrews

As part of an unintentional bump of the storybook version in
e8f9c1d it would no longer run
correctly.

The issue was already reported and relates to our webpack config
derived from CRA. storybookjs/storybook#2615

Понравилась статья? Поделить с друзьями:
  • Ошибка tamper терминала vx 520
  • Ошибка system error в python это
  • Ошибка system error title при запуске wot
  • Ошибка system data can be set
  • Ошибка system cnf файл не читается или поврежден