React Error: Target Container is not a DOM Element - javascript

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?

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.

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'));

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.

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>

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

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.

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)
}

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.

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
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>

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 .

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')
);

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

Related

Use JSX when using react loaded by <script> tag on html page

Is this possible to use JSX attributes, without bundler? (just using a HTML which is loading react in tag)
index.html file:
<html lang="en">
<body>
<div id="root"></div>
<script src="react.development.js" crossorigin></script>
<script src="react-dom.development.js" crossorigin></script>
<script src="index.js"></script>
</body>
</html>
index.js file:
class App extends React.Component {
render() {
return <div>Content</div>;
}
}
const e = React.createElement;
const domContainer = document.querySelector("#root");
ReactDOM.render(e(App), domContainer);
You need a transpiler, not a bundler. You can run one client-side, but shouldn't because it introduces performance problems (and can make it harder to debug your code).
This is covered in the documentation:
The quickest way to try JSX in your project is to add this <script>
tag to your page:
<script src="https://unpkg.com/babel-standalone#6/babel.min.js"></script>
Now you can use JSX in any <script> tag by adding
type="text/babel" attribute to it. Here is an example HTML file with
JSX that you can download and play with.
This approach is fine for learning and creating simple demos. However,
it makes your website slow and isn’t suitable for production. When
you’re ready to move forward, remove this new <script> tag and the
type="text/babel" attributes you’ve added. Instead, in the next
section you will set up a JSX preprocessor to convert all your
<script> tags automatically.

React with Babel without Node

I'm creating a React application without having to use npm or yarn, just want it to work by opening page.html file.
I have this code in both files, cockpit.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<link href="https://raw.githubusercontent.com/cockpit-project/cockpit/master/src/base1/cockpit.css" type="text/plain" rel="stylesheet">
<script src="https://raw.githubusercontent.com/cockpit-project/cockpit/master/src/base1/cockpit.js" type="text/plain"></script>
<script src="https://unpkg.com/react#16/umd/react.development.js" type="text/plain" crossorigin></script>
<script src="https://unpkg.com/react-dom#16/umd/react-dom.development.js" type="text/plain" crossorigin></script>
<script src="https://unpkg.com/babel-standalone#6/babel.min.js" type="text/jsx"></script>
<title>Cockpit Test</title>
</head>
<body>
<div id="root"></div>
<script type="text/babel" src="cockpitTest.jsx"></script>
</body>
</html>
and cockpitTest.jsx:
"use strict";
const rootElement = document.getElementById('root')
class CockpitTest extends React.Component {
componentDidMount() {
console.log("asd")
}
render() {
return (
<div>
<h1>test</h1>
</div>
);
}
}
function App(){
return(
<div>
<CockpitTest name="Test"/>
</div>
)
}
ReactDOM.render(<App />, document.getElementById('rootElement'))
but still I'm getting a blank screen when h1 text is expected. Console doesn't say anything either, it's just blank. Any help would be appreciated!
You have lots of problems
Content-Type
You've set type attributes on all your script and link elements to tell the browser that the CSS and scripts are in formats it doesn't understand. Don't do that.
Only the JSX file itself (in your last <script>) should have a type attribute.
Github is not a hosting service
You are trying to host the cockpit files on raw.github.com. This is not designed to be used as a CDN and returns data with the wrong Content-Type header. Use a real hosting service.
URL
You named the file cockpit.jsx but said src="cockpitTest.jsx"
Missing element
You said document.getElementById('rootElement') but also id="root". These do not match.
You are working without Node.js
The developer tools for React use Node.js to compile it for production-level performance. There's very little reason to not use them all the way through the development process.
First make it a javascript file .js
Then you can either:
Change:
rootElement = document.querySelector('#root'));
AND:
ReactDOM.render(<App />, rootElement)
OR:
ReactDOM.render(<App />, document.querySelector('#root'))
AND:
Delete your constant.
I even got React Router to work, but had problems when it came to separating components out into files for a tidy structure. Couldn't get imports to work inside app.js. Seems like Babel should have helped with imports and exports, but I couldn't get it to work.
Firstly - on your script type your using type "application/babel". This is not a valid media type, you probably want to use "application/javascript". This could be why nothing is displayed.
Secondly - the script you're using is not valid JS, you're using JSX which browsers cannot understand. JSX is what allows us to write html-like tags in JavaScript (the < /> for example). You would either have to write JS instead of JSX, or transpile your JSX using a transpiler such as babel. I would suggest running a compiler such as babel.
Read more about JSX here.

ReactDOM Uncaught SyntaxError: Unexpected token <

I'm sorry to ask such a specific question but I'm working on a simple tutorial which introduces React with the following HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Hello Separate</title>
</script>
</head>
<body>
<h1>Hello Separate</h1>
<div id="app"></div>
</body>
</html>
And a script to create a <p> within the div id ="app" using ReactDOM
ReactDOM.render(
<p>Rendered by React</p>,
document.getElementById("app")
)
I've provided the code in a fiddle here:
I don't understand why I'm getting the error Uncaught SyntaxError: Unexpected token < but think it's coming from the ReactDOM.render function, can anyone provide insight? Thank you!
Two issues with your code,
First
Your scripts are not proper. As per docs, you should add these scripts,
<script src="https://unpkg.com/react#16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom#16/umd/react-dom.development.js" crossorigin></script>
<script src="https://unpkg.com/babel-standalone#6/babel.min.js"></script>
Second
Might be you are writing your JS code in external JS file.
From the docs,
Now you can use JSX in any <script> tag by adding type="text/babel" attribute to it.
You need to add this script in your HTML file only,
<script type="text/babel">
ReactDOM.render(
<p>Rendered by React</p>,
document.getElementById("app")
)
</script>
Demo
As Emile Bergeron mentioned you're actually writing JSX, so you need 'build'
or transpile the code in regular JavaScript.
However if you're using just JSFiddle, they can transpile the code for you like this.
If you're working locally you can look into create-react-app as they mentioned or babel and webpack to build/bundle your files.
yes you might be right, you will might need to change: <p>Rendered by React</p> to either '<p>Rendered by React</p>' or "<p>Rendered by React</p>"
like this:
ReactDOM.render(
"<p>Rendered by React</p>",
document.getElementById("app")
)
you have to always enclose text or html in ".."

two problems on implementing react without create-react-app?

I am creating a simple react app to practice creating stuffs without dependencies provided by create-react-app (webpack - babel ....)
I am faced with two problems
this is the code:
HTML
<html>
<head><head>
<body>
<div id="App"> </div>
<script type="module" src="script.js" ></script>
<script crossorigin src="https://unpkg.com/react#16/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#16/umd/react-dom.production.min.js"></script>
</body>
</html>
JS
window.onload = () => {
class App extends React.Component {
render() {
return(
<div className="App">
<p>any paragraph</p>
</div>
)
}
}
ReactDom.render(App, document.getElementById('App'))
}
The first problem is:
Nothing is happening when adding the type attribute to the script tag and set its value to "module", nothing works at all, as if js engine could not access the script!!
The second problem:
After removing type="module", it works but with a console error Uncaught SyntaxError: Unexpected token <
So why these two problems happens and how to solve them??
Try loading script.js last. That is, after react-dom is loaded.

Accessing DOM elements react JS

I am new to react JS. I'm using react JS in conjunction with an existing Rails app.
With the help of webpacker gem i have all the dependencies available.
For some reason DOM elements are not available to react JS. In tutorials the same thing works fine.
In an html.erb file i have
<div id='root' data-link='https://x.com'></div>
app/javascript/index.js file
const root = document.querySelector('#root')
ReactDOM.render(<Dashboard link={root.dataset.link} />, root)
Uncaught TypeError: Cannot read property 'dataset' of null
Also, is it possible without the use of Refs or Portals that I can have above working.
The div with id root can't be found in the DOM because the script tag is before the div in the document. You could move the script tag after the div and it will work as expected.
<div id='root' data-link='https://x.com'></div>
<script src="/bundle.js"></script>
function Dashboard(props) {
return <h1>Hello, {props.link}</h1>;
}
const root = document.querySelector('#root')
ReactDOM.render(<Dashboard link={root.dataset.link} />, root)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id='root' data-link='https://x.com'></div>
It's totally workable, guess you might need to put some breakpoints and check if root has been passed correctly.

Categories