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.
Related
I'm trying to generalize my code by keeping a .js file containing only React components in one file and then utilizing these components in an HTML file. Here is my simple component:
component.js
'use strict'
class MyComponent extends React.Component {
render() {
return (
<div className="MyComponent">
<p>Text goes here.</p>
</div>
);
}
}
If in my component.js file I add: ReactDOM.render(<MyComponent/>, document.querySelector('#div-1')); and then, in my HTML, add <script src="component.js" type="text/jsx"></script> the React component shows in my page as expected.
However, my end goal is to be able to add the ReactDOM.render into my HTML within a script tag, that way I can have multiple pages utilizing the component.js components while doing all the assigning in the HTML page. Something like:
mypage.html (simplified)
<!DOCTYPE html>
<html>
<script src="component.js" type="text/jsx"></script> //import my components (no assigning done in this file)
<div id="div-1"><div>
<script>
ReactDOM.render(<MyComponent/>, document.querySelector('#div-1')); //assign to div
</script>
</html>
However this above code fails, with many errors regarding Uncaught SyntaxError: Unexpected token '<'
With that, how would I go about carrying something like this out? Any help is greatly appreciated.
The issue you're facing is that JSX isn't recognized by default in a browser.
Uncaught SyntaxError: Unexpected token '<' that's what this error means.
React docs have following help regarding that: quickly try JSX
you need to add babel in script tags and add type="text/babel" in whichever script you're using JSX.
<div id="counter_container"></div>
<!-- add babel support -->
<script src="https://unpkg.com/babel-standalone#6/babel.min.js"></script>
<!-- Load our React component. -->
<script src="components.js"></script>
<script type="text/babel">
(() => {
const Counter = window.Counter;
const counterContainerEl = document.querySelector('#counter_container');
ReactDOM.render(<Counter/>, counterContainerEl);
})();//this is just to avoid polluting global scope
</script>
I've put together a short example here github-repo
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.
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 ".."
I am learning reactjs through a tutorial and ran into this error. That says "Cannot read property 'keys' of undefined" My code is very minimal so I assume that it has to do with the structure of the language. Does anyone know the problem and a possible solution?
<!DOCTYPE html>
<html>
<head>
<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.min.js"></script>
<title>ReactJs</title>
</head>
<body>
<div id="app"></div>
<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.getElementById('app'));
</script>
</body>
</html>
Edit: oddly, after our comments above, I checked to see if it was indeed the babel core version, I am using this one in my fiddle:
https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.24/browser.js
The second I switch to your version above I get this:
Uncaught TypeError: Cannot read property 'keys' of undefined
Use React.createClass not ReactDOM.createClass and wrap multiple lines of html in parenthesis like so:
Working Example: https://jsfiddle.net/69z2wepo/38998/
var Hello = React.createClass({
render: function() {
return (
<div>
<h1>Hello World</h1>
<p>This is some text</p>
</div>
)
}
});
ReactDOM.render(
<Hello name="World" />,
document.getElementById('container')
);
Just to be clear, as the other answers are a bit convoluted. The problem was using "babel-core" instead of "babel-standalone". Just look up for a cdn for babel-standalone instead.
https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.26.0/babel.js
Today is my first day with React, and I've faced this issue when I tried to use Babel to transpile the JSX!
The issue is the version you are trying to use, please use this one instead:
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.25.0/babel.min.js"></script>
Don't forget to write type="text/babel" in the <script> tag which you will write the JSX in to let Babel transpile it for you, if you don't, you will find this error (As I have faced it too! :D):
Uncaught SyntaxError: Unexpected token <
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.29/browser.js"></script>
This is the version of babel-core which isn't giving me the error as shown below:
If you want to use the latest version, You can use the latest standalone version. (as per 22-Nov-2018)
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.24.0/babel.js"></script>
But this gives the following warning :
"You are using the in-browser Babel transformer. Be sure to precompile your scripts for production - https://babeljs.io/docs/setup/"
I haven't worked with React before, but there are a few things that I see that may be causing your issues. First, React.createClass instead of ReactDOM.createClass. Second, you need to wrap your html in parentheses:
var HelloWorld = React.createClass({
render: function() {
return (
<div>
<h1>Hello World</h1>
<p>This is some text></p>
</div>
);
}
});
This should get it working
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