ReactDOM Uncaught SyntaxError: Unexpected token < - javascript

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

Related

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.

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.

ReactJS:cannot display html text on browser

I cannot seem to figure out what I shall do to correct the issue:
I always got no display on the browser, where I expect to see "Hello React".
Here is the HelloWorld code:
ReactDOM.render(Hello, React!,document.getElementById('root'));
You can use following code base to understand basic of React JS (have been used latest version react-15.0.0) -
<!DOCTYPE html>
<html lang="en">
<head>
<title>My First React Example</title>
<!-- use this as script file "fb.me/react-15.0.0.js"
"fb.me/react-dom-15.0.0.js"
cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.34/browser.min.js" -->
</head>
<body>
<div id="greeting-div"></div>
<script type="text/babel">
var Greeting = React.createClass({
render: function() {
return ( <div>{this.props.children} </div>)
}
});
ReactDOM.render(
<div>
<Greeting>hello Aby</Greeting>
<h1>HELLO</h1>
</div>,
document.getElementById('greeting-div') );
</script>
</body>
</html>
check your example here, https://codesandbox.io/s/ElRmqWK5Y
what I will suggest download the react package and run your code there in the beginning, and what I think about your code is you should add react library first than react-dom.
there is a missing < body > in your code , try to add it and tell us if it works
So basically the problem is that you don't transpile your jsx. For your simple example what you can do if you don't want to configure transpiling 'explicitly' with some bundler you can add Babel library and change
<script type="text/jsx">
to
<script type="text/babel">
Let's have a look here, but please remember that jsfiddle uses babel behind (quite sure):
https://jsfiddle.net/69z2wepo/83023/
Also let me paste example from babel docs. Especially take a look for added babel lib + script type.
<div id="output"></div>
<!-- Load Babel -->
<script src="https://unpkg.com/babel-standalone#6/babel.min.js"></script>
<!-- Your custom script here -->
<script type="text/babel">
const getMessage = () => "Hello World";
document.getElementById('output').innerHTML = getMessage();
</script>

React JS Cannot read property 'keys' of undefined

I am beginning to learn React through a tutorial, however I ran into this error when I ran the code that I created.
The error seems to be one that has to do with the framework of the languages. Perhaps with the version of Babel that I imported for the translation.
Does anyone know the actual situation and how to find a soulution.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.1/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.1/react-dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/6.1.19/browser.js"></script>
<title>ReactJs</title>
</head>
<body>
<script type="text/babel">
var HelloWorld = ReactDOM.createClass({
render: function() {
return <div>
<h1>Hello World</h1>
<p>This is some text></p>
</div>
}
});
ReactDOM.render(<HelloWorld/>, document.body);
</script>
</body>
</html>
I'm not sure if you have found the results yet, but I got the same error and found out it's the cdn version mismatch issues.
If you use these cdn's:
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.3/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.29/browser.js"></script>
and change your
ReactDOM.render(<HelloWorld/>, document.body);
to
React.render(<HelloWorld/>, document.body);
it will work now.
babel-browser is deprecated. use babel-standalone https://github.com/babel/babel-standalone instead:
<script src="https://unpkg.com/babel-standalone#6/babel.min.js"></script>
React.render has been deprecated since React 0.14 (released October 7, 2015):
https://facebook.github.io/react/blog/2015/10/07/react-v0.14.html
I'd strongly recommend the awesome Create React App NPM module from Facebook, which creates React apps with no configuration, but still uses the latest ES6 and Babel features. Also it comes with hot reloading out of the box and has a build option, for creating a minified, bundled .js file ready for production.
https://github.com/facebookincubator/create-react-app

React Error: 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?
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

Categories