i need help for integrate frontend ReactJS on my site. currently i avoid to use nodeJS or NPM for implement my reactJS. but i'm using ReactJS CDN. so i not run npm start when develop the reactJS. i just want to use the frontend.
Hope this will understand from the start. so i have a question, how do i able to get another component and place it on single file.
I Created file App.js. I plan that this file will become a centralize for other components.
let me share what i'm doing right now.
here is my file structure
this is my code on index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Buynow Project</title>
<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>
<script type="text/babel" src="buynow/index.js"></script>
</head>
<body>
<div id="root"></div>
</body>
</html>
this is my code on index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.js'
ReactDOM.render(<App />, document.getElementById('root'));
this is my code on App.js
import React from 'react';
import Navbar from './components/Navbar.js'
function App(props){
return (
<div>
<Navbar/>
Hello App
</div>
);
}
export default App;
this is my code on Navbar.js
import React from 'react';
function NavBar(props) {
return (
<div>
<Navbar/>
Hi NavBar
</div>
);
}
export default NavBar;
but i got this error, and pointed on file index.js line:1
Uncaught ReferenceError: require is not defined
this is error
I confuse how to solve this. I start with the simple code just for testing if it can work or not.
please help.
https://reactjs.org/docs/react-without-jsx.html
JSX is not a requirement for using React. Using React without JSX is
especially convenient when you don’t want to set up compilation in
your build environment.
So you can't use JSX/TSX directly in your browser (need compilation). Also, you can't use import outside a module (so basically now, you can already use your function components by adding the import of all your files in the index.html).
In my experience I suggest that you use the benefits of JSX / TSX and compile your code with NPM to be more comfortable (everything is way more intuitive with jsx).
In any case, in the link that I have included, you will find how to do the equivalent of JSX with pure javascript. That's what you need. (as you can see in my small snippet)
If you want keep using react from CDN and without compiling, your code, should be something like this:
// For the Snippet i have all of your js here
// But you could just import in your index.html every separate component file you have (without any import/export syntax)
function NavBar(props) {
return React.createElement('span', null,props.title);
}
function App(props){
return React.createElement('span', null, React.createElement(NavBar, {title: 'Header'}, null),
React.createElement('span', null,'Hello App'));
}
ReactDOM.render(React.createElement(App, {}, null), document.getElementById('root'));
<html>
<head>
<meta charset="UTF-8" />
<title>Buynow Project</title>
<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>
</head>
<body>
<div id="root"></div>
</body>
</html>
Anyway, as you see, the code is not so readable this way...
EDIT
I made the same snippet on stackblitz with separated files
https://stackblitz.com/edit/web-platform-4ruju9?file=index.html
Ps. Also, don't put NavBar inside NavBar or you'll get a render loop
You have to enable module support in script tag
<script type="text/babel" data-type="module" src="./index.js"></script>
Remove React import statements as they can be directly used.
What do I need to make the following work?
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.26.0/babel.min.js"></script>
</head>
<body>
<script type="text/babel">
import React from 'react';
</script>
</body>
</html>
In its current form it produces an error:
Inline Babel script:2 Uncaught ReferenceError: require is not defined
at <anonymous>:3:14
at run (babel.js:61531)
at check (babel.js:61597)
at loadScripts (babel.js:61638)
at runScripts (babel.js:61668)
at transformScriptTags (babel.js:336)
at babel.js:327
This form does not work too:
import React from 'react.production.min';
If you are building a React application with client-side babel: You don't use import.
import React from 'react'; is replaced by the first two <script> elements you have in your HTML document.
If you want to use modules with React, you'd be better off taking "Setup Option 2" in the React tutorial and putting together a local development environment that uses babel at build time instead of at run time.
I have just started learning ReactJS and made my first app by following a tutorial but nothing is rendered on the screen when I run the html file.
index.js
import React from "react"
import ReactDOM from "react-dom"
ReactDOM.render(<h1>Hello World</h1>, document.getElementById("root"));
index.html
<html>
<body>
<div id="root">
</div>
</body>
<script type="text/babel" src="index.js"></script>
</html>
Here I think you need to write your code in the form of function which would be called from the HTML file.
So you need to update your index.js to:
import React from "react"
import ReactDOM from "react-dom"
window.printHello = function(id){
ReactDOM.render(
<h1>Hello, world!</h1>,
document.getElementById(id)
);
}
And your html file should be updated to the below code:
<div id="hello"></div>
<script src="index.js"></script>
<script>
printHello('hello');
</script>
Here is another solution for your query.
There is no need to add the script tag in your HTML.
If the js and HTML are part of the same component you can just use the id directly in the HTML.
So your updated code for js and HTML would be be somewhat like this.
import React from "react"
import ReactDOM from "react-dom"
ReactDOM.render(<h1>Hello World</h1>, document.getElementById("root"));
And the HTML code:
<html>
<body>
<div id="root">
</div>
</body>
</html>
I hope this would be helpful to you.
For me the issue was ReactDOM getting imported from different module. After updating the import statement from
import ReactDOM from "react";
to
import ReactDOM from 'react-dom/client';
in index.js file worked.
Trying to get a very basic react/jspm example working over on plnkr.co but it is erroring out with a number of 404's. Most notably the following:
Uncaught (in promise) Error: XHR error (404 Not Found) loading https://npm.jspm.io/react-tools#0.13.3/vendor/fbtransform/visitors
Error loading https://npm.jspm.io/react-tools#0.13.3/vendor/fbtransform/visitors as "./vendor/fbtransform/visitors" from https://npm.jspm.io/react-tools#0.13.3/main.js
Error loading https://registry.jspm.io/js/app.jsx.js!https://registry.jspm.io/jsx.js
at r (https://jspm.io/system#0.18.17.js:5:11565)
at XMLHttpRequest.o.onreadystatechange (https://jspm.io/system#0.18.17.js:5:12090)
Any thoughts on how to get past these and get the sample to render?
--> problem plnkr.co sample here <--
The code was also copied in the following code snippet (which obviously will never work here as different JSX files are required) just for SO readers that doesn't want to go to plnkr.co.
// app.jsx
import React from 'react'
import Test from './test.jsx!'
React.render(
<Test />
, document.getElementById('main')
);
//------------------------------
// test.jsx
import React from 'react'
export default React.createClass({
displayName: 'Test'
, render: function () {
return (
<div>Awesome Test!</div>
)
}
})
//------------------------------
//config.js
System.config({
});
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="main"></div>
<script src="https://jspm.io/system#0.18.17.js"></script>
<script type="text/javascript" src="config.js"></script>
<script type="text/javascript">
System.import('js/app.jsx!jsx')
</script>
</body>
</html>
You have these problems:
index.html: System.import('js/app.jsx!jsx') should have been System.import('./app')
app.jsx: import Test from './test.jsx!' should have been import Test from './test'
Missing map to your libraries in config.js:
System.config({
map: {
"react": "npm:react#0.13.3"
}
});
Here is the fixed plunker
I get this error after a making trivial React example page:
Uncaught Error: Invariant Violation: _registerComponent(...): Target container is not a DOM element.
Here's my code:
/** #jsx React.DOM */
'use strict';
var React = require('react');
var App = React.createClass({
render() {
return <h1>Yo</h1>;
}
});
React.renderComponent(<App />, document.body);
HTML:
<html>
<head>
<script src="/bundle.js"></script>
</head>
<body>
</body>
</html>
What does this mean?
By the time script is executed, document element is not available yet, because script itself is in the head. While it's a valid solution to keep script in head and render on DOMContentLoaded event, it's even better to put your script at the very bottom of the body and render root component to a div before it like this:
<html>
<head>
</head>
<body>
<div id="root"></div>
<script src="/bundle.js"></script>
</body>
</html>
and in the bundle.js, call:
React.render(<App />, document.getElementById('root'));
You should always render to a nested div instead of body. Otherwise, all sorts of third-party code (Google Font Loader, browser plugins, whatever) can modify the body DOM node when React doesn't expect it, and cause weird errors that are very hard to trace and debug. Read more about this issue.
The nice thing about putting script at the bottom is that it won't block rendering until script load in case you add React server rendering to your project.
Update: (October 07, 2015 | v0.14)
React.render is deprecated, use ReactDOM.render
instead.
Example:
import ReactDOM from 'react-dom';
ReactDOM.render(<App />, document.getElementById('root'));
/index.html
<!doctype html>
<html>
<head>
<title>My Application</title>
<!-- load application bundle asynchronously -->
<script async src="/app.js"></script>
<style type="text/css">
/* pre-rendered critical path CSS (see isomorphic-style-loader) */
</style>
</head>
<body>
<div id="app">
<!-- pre-rendered markup of your JavaScript app (see isomorphic apps) -->
</div>
</body>
</html>
/app.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App';
function run() {
ReactDOM.render(<App />, document.getElementById('app'));
}
const loadedStates = ['complete', 'loaded', 'interactive'];
if (loadedStates.includes(document.readyState) && document.body) {
run();
} else {
window.addEventListener('DOMContentLoaded', run, false);
}
(IE9+)
Note: Having <script async src="..."></script> in the header ensures that the browser will start downloading JavaScript bundle before HTML content is loaded.
Source: React Starter Kit, isomorphic-style-loader
the ready function can be used like this:
$(document).ready(function () {
React.render(<App />, document.body);
});
If you don't want to use jQuery, you can use the onload function:
<body onload="initReact()">...</body>
just a wild guess, how about adding to index.html the following:
type="javascript"
like this:
<script type="javascript" src="public/bundle.js"> </script>
For me it worked! :-)
I ran into the same error. It turned out to be caused by a simple typo after changing my code from:
document.getElementById('root')
to
document.querySelector('root')
Notice the missing '#'
It should have been
document.querySelector('#root')
Just posting in case it helps anyone else solve this error.
Yes, basically what you done is right, except you forget that JavaScript is sync in many cases, so you running the code before your DOM gets loaded, there are few ways to solve this:
1) Check to see if DOM fully loaded, then do whatever you want, you can listen to DOMContentLoaded for example:
<script>
document.addEventListener("DOMContentLoaded", function(event) {
console.log("DOM fully loaded and parsed");
});
</script>
2) Very common way is adding the script tag to the bottom of your document (after body tag):
<html>
<head>
</head>
<body>
</body>
<script src="/bundle.js"></script>
</html>
3) Using window.onload, which gets fired when the entire page loaded(img, etc)
window.addEventListener("load", function() {
console.log("Everything is loaded");
});
4) Using document.onload, which gets fired when the DOM is ready:
document.addEventListener("load", function() {
console.log("DOM is ready");
});
There are even more options to check if DOM is ready, but the short answer is DO NOT run any script before you make sure your DOM is ready in every cases...
JavaScript is working along with DOM elements and if they are not available, will return null, could break the whole application... so always make sure you are fully ready to run your JavaScript before you do...
If you use webpack for rendering your react and use HtmlWebpackPlugin in your react,this plugin builds its blank index.html by itself and injects js file in it,so it does not contain div element,as HtmlWebpackPlugin docs you can build your own index.html and give its address to this plugin,
in my webpack.config.js
plugins: [
new HtmlWebpackPlugin({
title: 'dev',
template: 'dist/index.html'
})
],
and this is my index.html file
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="shortcut icon" href="">
<meta name="viewport" content="width=device-width">
<title>Epos report</title>
</head>
<body>
<div id="app"></div>
<script src="./bundle.js"></script>
</body>
</html>
In my case this error was caused by hot reloading, while introducing new classes. In that stage of the project, use normal watchers to compile your code.
For those using ReactJS.Net and getting this error after a publish:
Check the properties of your .jsx files and make sure Build Action is set to Content. Those set to None will not be published. I came upon this solution from this SO answer.
I ran into similar/same error message. In my case, I did not have the target DOM node which is to render the ReactJS component defined. Ensure the HTML target node is well defined with appropriate "id" or "name", along with other HTML attributes (suitable for your design need)
When you got:
Error: Uncaught Error: Target container is not a DOM element.
You can use DOMContentLoaded event or move your <script ...></script> tag in the bottom of your body.
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.
document.addEventListener("DOMContentLoaded", function(event) {
ReactDOM.render(<App />, document.getElementById('root'));
})
it's easy just make basic HTML CSS js and render the script from js
mport React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
var destination = document.querySelector('#container');
ReactDOM.render(
<div>
<p> hello world</p>
</div>, destination
);
body{
text-align: center;
background-color: aqua;
padding: 50px;
border-color: aqua;
font-family: sans-serif;
}
#container{
display: flex;
justify-content: flex;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<title> app </title>
</head>
<body>
<div id="container">
</div>
</body>
</html>
In my case of using jQuery - for some reason the window.onload doesn't act the same as jQuery's onload
So this one worked for me:
<script>
$(function () { <= replacing window.onload = function() {
// Begin Swagger UI call region
const ui = SwaggerUIBundle({
...
window.ui = ui;
});
</script>
In my case, everything in the html file was set correctly (i.e. script was at the bottom of the body tag). The problem was solved by moving the definition of a component to a separate file from where the component was rendered to the ReactDOM.
So originally I had
import React from 'react';
import ReactDOM from 'react-dom';
class Comp extends React.Component {
// component definition
}
ReactDOM.render(
<Comp />,
document.getElementById('root')
);
Problem was solved after I moved the component definition to a separate file and imported
import React from 'react';
import ReactDOM from 'react-dom';
import Comp from './CompFile';
ReactDOM.render(
<Comp />,
document.getElementById('root')
);
For my case I did mistake something below in index.js and corrected.
Error:
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
Solution: document.getElementById("root")
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById("root") // declared
);
With webpack. there is a choice to load the html file with the htmlPlugin instead of us needing to define it. When this is the case, Webpack is going to create an html file that has the script tag over above the root-div element. One quick fix would be to add a new div to the dom dynamically and then write your react dom to it. This can be done on your reactDom render function defined (usually) on the index.js file as below.
import React from "react";
import ReactDOM from "react-dom";
import App from "./components/App";
import { BrowserRouter as Router } from "react-router-dom";
ReactDOM.render(
<Router>
<App />
</Router>,
document.body.appendChild(document.createElement("div"))
);