Error: Target container is not a DOM element BASIC REACTJS - javascript

I'm learning React, and I was watching a tutorial in YT (https://youtu.be/7MmncixTZOo), the thing is that I'm just trying to print a text in my main file but doesn't work (the screen remains blank).
This is my package.json (to check versions, I think React syntax is updated, can be?)
I just deleted all the files in the "src" folder and created these two ("index.js" and "App.js").
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App';
ReactDOM.render(<App />, document.querySelectorAll('#root'));
App.js
import React from 'react';
const App = () => {
return <div>App</div>
};
export default App;
I get this error:
(I know that the error gives it because there is not created the element ID "root", but if I believe it, my screen is blank and it doesn't print the text "App").
Can someone lend me a hand?
Thanks a lot of!!!
Cheers.
EDIT: This is my index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<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"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>

Inside your index.html file in your public folder you should have a code like this <div id='root'></div> where root targets your unique div element.
And in your index.js file you should not call a collection with document.querySelectorAll('#root') because it returns a collection even if only one occurence matches the selector.
Use instead document.querySelector('#root') to target the first selector that is found.
Technically speaking you can event change the id property name into mammy inside your index.html file like this <div id='mammy'></div>.As it mammy in your index.js it will be document.querySelector('#mammy').It just to help you understand how things really work
I hope that it helped

You have used
document.querySelectorAll
that will return a collection of elements not an element.
You need to use:
document.getElementById('root')

Related

Using react with normal HTML/JavaScript to run without using npm/node

Suppose you have an application that was developed using the Java Spring framework and deployed on a Tomcat server, also, the application uses AngularJS for most of the front-end application parts.
I am thinking of using React to add HTML components to customize the front-end parts of the application instead of using AngularJs. I did follow React tutorials and realized that you need to have node and npm installed and spin up a server to run the application using npm run start to preview the React Web Application. I wonder how you can include "React components" on a regular HTML/JavaScript page and run this component on the browser without the need to use npm run start. I am trying to avoid the need to install node/npm on the target machine where the Java Spring-based web application is running.
I don't plan to integrate AngularJS with React. All I want to do is to add React HTML/JSX components since I noticed it is much easier than Angular in general.
Is it possible to include the needed libraries for React dependencies along with the target application using the script tag on the main index.htm web page then I can start adding React components as usual?
After installing the react sample project using npx create-react-app react-prj you get the below index.js and a bunch of other libraries and application parts:
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
reportWebVitals();
And you get the below main HTML file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<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"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>
As mentioned, if you open the above HTML in the browser, you will get an empty page, and you must run the app using npm run start.
How I can get a setup for a sample React web application without using node/npm and I just want to use a normal HTML/JavaScript application to be run on the browser directly?
Is this possible?
Thanks to #Sean. Also, I found a good reference here:
https://stackoverflow.com/a/56504616/4180447
I managed to implement React without npm as follows:
Create the sample app using npx create-react-app sample-prj as usual.
Modify the HTML and JavaScript files as follows:
/public/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="favicon.ico" />
<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"
/>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>React App</title>
<link rel="stylesheet" href="../src/App.css">
<link rel="stylesheet" href="../src/index.css">
<script crossorigin src="https://unpkg.com/react#18/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#18/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/#babel/standalone/babel.min.js"></script>
<script src="../src/App.js" type="text/babel" data-plugins="transform-modules-umd" defer ></script>
<script src="../src/index.js" type="text/babel" data-plugins="transform-modules-umd" defer></script>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>
/src/App.js
// import logo from './logo.svg';
// import './App.css';
function App() {
const logo = '../src/logo.svg';
return (
<div className="App">
<p>This is paragraph</p>
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React xxx
</a>
<div>This is a test with Tarek and Firas</div>
</header>
<p>This is paragraph</p>
<div>This is a test with Tarek and Firas</div>
</div>
);
}
export default App;
/src/index.js
// import React from 'react';
// import ReactDOM from 'react-dom/client';
// import '/src/index.css';
import App from '/src/App.js';
// import reportWebVitals from './reportWebVitals';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint.
// reportWebVitals();

How to apply CSS style to HTML file that is inside the public folder of React JS

I'm learning React JS.I can apply CSS style to components that is inside the src folder.
But here is the query, how can I apply CSS style to a body tag of HTML file which is sitting inside the public folder. I have tried putting the CSS style inside the HTML file but it's not reflecting.How can I apply CSS stylle from src folder to HTML file of public folder? is that possible?
<link rel='stylesheet' href='style.css'/>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<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"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>
I have CSS file inside the src folder and imported it to index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import 'bootstrap/dist/css/bootstrap.css'
import './style.css'
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App/>)
You can search for your global CSS file (App.css or index.css).
body,
html {
//your style
}
You can add your style to your style.css file. Adding style in the public/index.html file is not the best practice
body {
// your style
}
Add style.css in your root project (Not in a public folder!) then import it in your index.js file like:
import "./style.css"
Your App component should include react components in itself in src folder. Each of those react components can have styling via import. For example:
import "./YourComponentName.css"
When you import styling in a react component, it is rendered with all other files to main App component and they directly affect html file in public folder.
In other words, no need to change html file in public folder. Just import styling at the top of component file and ,if it's rendered correctly, styling will be visible.
To change body of that html file in public directory , import styling to index.js file in src folder, and address the body tag in css (without dot before the tag , which will make body as a class reference )

How to use CDN javascript in React

I want to use javascript simple component in React.
for example wavesurfer.js
It is easy to use, if you don't use react.
<head>
<script src="https://unpkg.com/wavesurfer.js"></script>
</head>
<script>
let wavesurfer = WaveSurfer.create({
container: '#waveform',
waveColor: 'violet',
progressColor: 'purple'
});
</script>
<html>
<div id="waveform"></div>
</html>
It works well only this code.
So,I try to do the same thing in React.
I put <script src="https://unpkg.com/wavesurfer.js"></script>
in public/index.html
and then made class.
class Waveform extends Component {
componentDidMount(){
let wavesurfer = WaveSurfer.create({
container: '#waveform',
waveColor: 'violet',
progressColor: 'purple'
});}
render() {
return (
<div id="waveform"></div>
);
}
};
However, it shows error
'WaveSurfer' is not defined no-undef
In my understanding, wavesurfer.js is read from CDN in head
Why WaveSurfer class is not found??
my index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<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"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
<script src="https://unpkg.com/wavesurfer.js"></script>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>
I would advise you to do a var require instead :
var WaveSurfer = require('wavesurfer.js')
Maybe it could be more efficient than the unpkg script
Who must have crashed the extraction of the package and who could not load it.
It can only be an error coming from the loading of the library which could not be carried out.
You can use node js or yarn in particular to install this library.
npm install wavesurfer.js --save
# or
yarn add wavesurfer.js
Then simply import the library and use it as you see fit with the available variables :
import WaveSurfer from 'wavesurfer.js';
var WaveSurfer = require('wavesurfer.js');
define(['WaveSurfer'], function(WaveSurfer) {
// ... code
});
If that didn't really help you, please re-read the API site below, hoping it was a great help.
https://wavesurfer-js.org/api/
This looks like a typescript (possibly other linter error). You need to disable the no-undef rule for this line. There is no way the parser can know at design/compile-time that this will be a defined at runtime when the page renders.
That error is from an eslint rule. Add a comment above the relevant line: // eslint-disable-next-line no-undef, or add it to your globals in your eslint config. It's not breaking your app, just breaking the linting.
My recommendation to you is simple. Install the NPM package. Will save you a lot of time.

Why does React code work without any errors?

I have some question.
I had started React tutorial this page. And I created React project by using 'create-react-app' and delete some files (/src/App.js .. etc.). Finally I written code below and running code.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<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"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<title>React App</title>
</head>
<body>
<div id="root"></div>
</body>
</html>
index.js
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import './index.css';
class App extends Component {
render() {
return(
<div className="App">
<h1>Hello, React!</h1>
<h2>Created react-tutorial</h2>
</div>
)
}
}
ReactDOM.render(<App/>, document.getElementById('root'));
So, I don't know why no error in running this project. I looked at the 'index.html', but there was no script link tag. Why have no errors? Because I used 'create-react-app'?
PS. Some contexts may be strange because I used some Google translate service. Sorry :(..
If you are using create-react-app to bootstrap your project then you need to be aware that create-react-app has a couple of things abstracted, which makes it easy to create a react app without having to bother about scripts, configuration and build tools.
From the Docs, it was stated that for the project to build, these files must exist with exact filenames:
public/index.html is the page template;
src/index.js is the JavaScript entry point.
Here's a link to the Getting Started guide, I hope this helps. Good luck!
P.S From your code - index.js, I can see you still have a reference to index.css, just wanted to point this out since you said you deleted everything. You might also want to take out the two <link> tags in the index.html file which is referencing an image and the manifest.json file from the public folder (if they don't exist anymore)

ReactDOM.render() query

I have started to build a demo project after learning React from some online tutorials.
Please consider the line of code below from a ReactComponent.
ReactDOM.render(<Home/>, document.getElementById('container'));
This renders the React component Home at the target DOM element container. All the tutorials online showed that this renders it in some index.html file. How does the code know, in which HTML(document) file to find the DOM element container. Below is the screenshot of the error I am getting.
Below is my index.html which is the default one from scaffolding.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="theme-color" content="#000000">
<!--
manifest.json provides metadata used when your web app is added to the
homescreen on Android. See https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json">
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<noscript>
You need to enable JavaScript to run this app.
</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>
With React, as all JavaScript, it's loaded into the file via an HTML file (i.e., the HTML file comes first). Your JavaScript is usually imported with a <script> tag. It's that HTML file currently open in the browser that it should look in.
So, you should have something like this for your HTML file, which you open in the browser:
<!DOCTYPE html>
<head>
<script src="./src/Home.js"></script>
<body>
<div id="container"></div>
Opening that, assuming the JS path is correct, should work fine.

Categories

Resources