React.Js not rendering in django project - javascript

i am creating a project where react is not rendering anything on django localhost
index.html
<!DOCTYPE html>
<html lang="en">
<head></head>
<body>
<div id="App">
<!---all will be define in App.js-->
<h1>Index.html </h1>
</div>
</body>
{% load static%}
<script src="{% static "frontend/main.js" %}"></script>
</html>
app.js
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import Header from './layout/header';
class App extends Component {
render() {
return (
<h1>App.JS</h1>
)
}
}
ReactDOM.render(<App />, document.getElementById('app'));
this is my project structure:
After running npm run dev and python manage.py runserver this is the status everything is fine till here:

Change this source code:
document.getElementById('app')
... to this:
document.getElementById('App')

Its because your element has id of "App" but you are trying to hook react app on element 'app'. It's case sensitive.

document.getElementById is case sensitive

Related

React not rendering anything on the DOM

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.

how to get React file recognized within Flask project

I'm currently trying to put together a little Flask + React project. I have had some difficulty getting the js file (which contains the react code) to run at all in the project.
This is my project structure, standard for flask:
The route is defined in the routes.py file in the project root
from flask import Flask, render_template, request
app = Flask(__name__)
#app.route("/qubits")
def qubits():
return render_template('qubits.html')
# http://localhost:5000/qubits
if __name__ == "__main__":
app.run(debug=True)
I have my simple html file, which is linking properly to my css (im able to pull in css elements fine).
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>nstem</title>
<link rel= "stylesheet" href= "{{ url_for('static',filename='css/nstem.css') }}">
</head>
<body>
<div class="indexBox1"></div>
<h1>: )</h1>
<script type="text/javascript"
src="{{ url_for('static', filename='js/index.js') }}"></script>
</div>
</body>
</html>
However, nothing is being returned on the webpage from these two js files:
*index.js*
import React from 'react';
import ReactDOM from 'react-dom';
import './nstem.css';
import Qubit from './qubits';
ReactDOM.render(
<Qubit />,
document.getElementById('root')
);
* function file *
import React from 'react';
import ReactDOM from 'react';
function Qubit() {
const section = 'lists';
return (
<div>Allah'u'abha</div>
);
}
export default Qubit;
Im pretty stumped; ive played with this so much today and cant figure out where the gap is. Please help, and thanks so much.

How to render an iframe using third party script in ReactJS

I am working on ReactJS project and want to render an iframe which is rendering using third party script.
Kindly check the problem below:
I have an component name add-data.js.
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import Helmet from 'react-helmet';
import ogImage from '../../../../public/images/qcf-logo-whitebg.svg';
import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom";
import ApplyNowNavbar from '../Header/ApplyNowHeader';
import ApplyNowFooter from '../Footer/ApplyNowFooter';
export default class ApplyNow extends Component {
render() {
return (
<div>
<Navbar />
<div id="iframe-container"></div> //iframe will be loadd inside this div
<Footer />
</div>
);
}
}
index.html main file
<!doctype html>
<html>
<head>
<script src="www.example.com/iframe-script.js"></script> <!--this file will load iframe in iframe-container div-->
</head>
<body>
<div id="app"></div>
<script src="../js/app.js"></script>
</body>
</html>
this code works only when reload the page but I want to render iframe without reload the page but render ReactJS component.
Can anybody help me out how can I do that.
Thanks in advance.

"Target container is not a DOM element" before building

I keep getting this error with React:
_registerComponent(...): Target container is not a DOM element.
I'm using "create-react-app" with Yarn. There's three main files of code.
Here's the index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hello World</title>
</head>
<body>
<div id="hw"></div>
</body>
</html>
And index.js:
import './index.css'
import React from 'react'
import {render} from 'react-dom'
import Hello from './Hello'
render(<Hello/>, document.querySelector('#hw'))
And Hello.js
import './helloworld.css'
import React, {Component} from 'react'
class Hello extends Component {
render() {
return
<div className="HelloWorld-hello HelloWorld-flex">
<h1>Hello</h1>
</div>
}
}
export default Hello
I've tried everything I can think of. All files are in the same "src" directory. This all started when I was trying to render two components within index.js using this:
render(
<div>
<Hello/>
<World/>
</div>,
document.querySelector('#hw'))
I found the issues, although I don't understand why one is happening. Apparantely, it's only working when I use root as the name of the div in index.html.
<body>
<div id="root"></div>
</body>
And index.js
import './index.css'
import React from 'react'
import ReactDOM from 'react-dom'
import Hello from './Hello'
import World from './World'
ReactDOM.render(<div><Hello/><World/></div>,
document.getElementById('root'))
In the Hello.js file, I placed the div outside of the line with return. Once I moved the div to start on that line.
import './helloworld.css'
import React, {Component} from 'react'
class Hello extends Component {
render() {
return <div className="HelloWorld-hello HelloWorld-flex">
<h1>Hello</h1>
</div>
}
}
export default Hello
I think I understand why I would need to put the <div> on the same line as the return, but I'm completely clueless about why only the word root works for the div id. I've tried all kinds of other words and get the same error.
Ultimately I was trying to have two separate child components (Hello.js and World.js) nested under a parent component (index.js).

Invariant Violation: _registerComponent(...): Target container is not a DOM element

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"))
);

Categories

Resources