I am trying to render a React component in an html file without using all too much code or too many files. The end goal is to let others render my React component in their html files with as little work for them as possible, hence the necessity for few files.
If I set up a project containing two files (index.html and index.js), one for defining the react component and another for rendering it, I do not get an error, but my component does not show up.
My files look like this:
index.html
<html>
<head>
<title>hello world</title>
</head>
<body>
<div>hello world</div>
<p>trying to load a react component</p>
<div id="root"></div>
</body>
</html>
index.js
import React from "react";
import { createRoot } from "react-dom/client";
const Component = () => {
return <div>hello this is literally react. not a joke LOL</div>;
};
const root = createRoot(document.getElementById("root"));
root.render(<Component />);
When I then run the project in the browser, the react component does not load whereas all other components do laod.
What do I do?
I´m a newbie on react and gatsby but i´m working on a little project as practice anda I have a little problem. I want to add a custom JS file to the project (little functions for a calculator on the index). I used Helmet to import them and on develop enviroment is working fine, but once build, is not.
import Helmet from "react-helmet"
import { withPrefix, Link } from "gatsby"
export default function homePage() {
return (
<main>
<Helmet>
<script src={withPrefix('/functions.js')} type="text/javascript" />
<script src={withPrefix('/escritura.js')} type="text/javascript" />
</Helmet>
}
I´m not sure what I am doing wrong. Someone can help me, please? You can see the project proof version live here:
https://modest-hoover-aac2d1.netlify.app/
In the final version, every input should be filled automatically, but is not happening.
withPrefix is a helper function that only works in build mode because in development mode paths don't need to be prefixed:
For pathnames you construct manually, there’s a helper function,
withPrefix that prepends your path prefix in production (but doesn’t
during development where paths don’t need to be prefixed).
So if your code works well under development mode, just remove withPrefix and leave your code as:
export default function homePage() {
return (
<main>
<Helmet>
<script src={`/functions.js`} type="text/javascript" />
<script src={`/escritura.js`} type="text/javascript" />
</Helmet>
}
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 got starting ASP.NET MVC project with the following resources added:
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/bootstrap")
<script src="~/Scripts/require.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.24.0/babel.js"></script>
<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>
#RenderSection("scripts", required: false)
Section scripts in Index.cshtml:
<div id="root"></div>
#section scripts
{
<script src="~/Scripts/ReactJS/Index.js" type="text/babel"></script>
}
And the file itself:
import React from 'react';
import ReactDOM from 'react-dom';
ReactDOM.render(
<h1>Hello, world!</h1>,
document.getElementById('root')
);
The result is empty page with no errors.
I do not want to use Node.js, I do not want to use even require.js and babel.js, but it seems I have to.
What are the minimal dependencies of reactjs to work properly?
First, ensure ReactJS core files & Remarkable.js referenced properly as this:
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/[version]/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/[version]/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/remarkable/[version]/remarkable.min.js"></script>
(more info: ReactJS MVC / ReactJS Core MVC)
Then, add JSX file in either <head> tag or Scripts section:
#section Scripts {
<script src="~/Scripts/ReactJS/Index.jsx"></script>
}
Assume in your <body> tag has this div container to bind...
<div id="root"></div>
Then, in JSX file the React script should be looks like this:
// Index.jsx
var Root = React.createClass({
render: function () {
return (
<h1>Hello, world!</h1>
);
}
});
ReactDOM.render(<Root />, document.getElementById('root'));
As the tutorial page said, BabelJS required if you want to use ES6 features such as arrow functions & concise methods, or use bundling mechanism (BabelBundle instead of plain ScriptBundle) to load JSX file.
Related issue:
ReactJS.NET MVC tutorial doesn't work?
Please use div before h1
var Root = React.createClass({
render: function () {
return (<div>
<h1>Hello, world!</h1> </div>);
}
});
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"))
);