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.
Related
I am self-learning react and I am just confused about a lot of things.
I thought that if I add React to my index.html via a script like the below:-
//index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bill Details</title>
</head>
<body>
<div id="billTable"></div>
<script src="BillTable.js" type="text/javascript"></script> ------------- Problem Line 1
</script>
</body>
</html>
and this is my js file where I am trying to return react component
//BillTable.js
import React from "react";
import ReactDOM from "react-dom";
function BillTable() {
return <h1>HELLO TABLE</h1>;
}
ReactDOM.render(<BillTable/>, document.getElementById("billTable"));
when I try to open index.html directly in firefox or through express server I get the below error in console:-
Uncaught SyntaxError: import declarations may only appear at top level of a module.
I then got rid of this error by changing the script type in problem line 1 in index.html to
<script src="BillTable.js" type="text/babel"></script>
but then also my webpage is completely blank and even console is not showing any errors.
Please suggest how to solve this issue. I am right now trying to learn React with functional approach only, so if any changes are required to be done on the react side, please make them in the functional approach.
I don't think you have included the correct packages to handle React components and JSX yet. These packages react, react-dom, etc. are usually in a package.json and are required to tell the browser what tools will be used to run the code. These packages handle the "script" or components you create and places the elements constructed in your components to the DOM. You can solve this by loading react with additional script tags before your component's script tag. This will let the browser know how and what to use to run your react component. Also, in your function, it does not know that it is a React Component. Check out an explanation for why you would have to use React.createElement I have attached an example of using only an index.html page here:
example of using an index.html page
Your Component file:
"use strict";
function BillTable() {
return React.createElement("h1", "", "HELLO TABLE");
}
const domContainer = document.querySelector("#billTable");
const root = ReactDOM.createRoot(domContainer);
root.render(React.createElement(BillTable));
and your index.html:
<body>
<div id="billTable"></div>
<!-- Load your React packages -->
<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>
<!-- Load your React component. -->
<script src="BillTable.js"></script>
</body>
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.
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 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
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