React Uncaught Error: Target container is not a DOM element [duplicate] - javascript

This question already has answers here:
Invariant Violation: _registerComponent(...): Target container is not a DOM element
(16 answers)
Closed 4 years ago.
I recently created my webpack config file:
const path = require("path");
const SRC_DIR = path.join(__dirname, "/client/src");
const DIST_DIR = path.join(__dirname, "/client/dist");
module.exports = {
entry: `${SRC_DIR}/index.jsx`,
output: {
filename: "bundle.js",
path: DIST_DIR
},
module: {
rules: [
{
test: /\.jsx?$/,
include: SRC_DIR,
exclude: /node_modules/,
loader: "babel-loader",
query: {
presets: ["react", "es2015"]
}
}
]
},
mode: "development"
};
This one works well and is bundling the jsx file:
import React from "react";
import ReactDOM from "react-dom";
class MainApp extends React.Component {
render() {
return (
<div className="content">
<h1>Hello World</h1>
</div>
);
}
}
ReactDOM.render(<MainApp />, document.getElementById("app"));
And now inside the html file I included the bundle file with the div id app.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>REACT TEST</title>
<script src="./bundle.js"></script>
</head>
<body>
<div id="app"></div>
</body>
</html>
When I tried to run this it seems it did not work and I got the error:
Uncaught Error: Target container is not a DOM element.
at invariant (invariant.js:42)
at legacyRenderSubtreeIntoContainer (react-dom.development.js:17116)
at Object.render (react-dom.development.js:17195)
at eval (index.jsx:48)
at Object../client/src/index.jsx (bundle.js:97)
at __webpack_require__ (bundle.js:20)
at bundle.js:84
at bundle.js:87
invariant # invariant.js:42
What am I missing here? Why I am getting this error?

The way you have it it runs before you even have DOM.
You should include it in the bottom like so:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>REACT TEST</title>
</head>
<body>
<div id="app"></div>
<script src="./bundle.js"></script>
</body>
</html>

You are inserting your React script before the initialization of the container. Make it like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>REACT TEST</title>
</head>
<body>
<div id="app"></div>
<script src="./bundle.js"></script>
</body>
</html>

Related

HTML button onclick function not recognised in JavaScript

I have an HTML file linked to a script. A button defined in the HTML has an onclick function 'incrementLabel()' but the function in the script throws the warning:
'incrementLabel' is declared but its value is never read.
function incrementLabel() {
var text = document.getElementById("testLabel").textContent;
document.getElementById("testLabel").innerText = (parseInt(text) + 1);
}
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css">
<script src="js/Main.js"></script>
<title>Test Web App</title>
</head>
<body>
<button onclick="incrementLabel()">Test</button>
<label id="testLabel">0</label>
</body>
</html>
I can't find any solutions to the problem other than writing the function in a in HTML. Any help would be much appreciated.
Thanks!
<!DOCTYPE HTML>
<script>
function incrementLabel() {
var text = document.getElementById("testLabel").textContent;
document.getElementById("testLabel").innerText = (parseInt(text) + 1);
}
</script>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css">
<script src="js/Main.js"></script>
<title>Test Web App</title>
</head>
<body>
<button onclick="incrementLabel()">Test</button>
<label id="testLabel">0</label>
</body>
</html>
This works perfectly fine. Check if you are importing your JS script correctly.
You can put the javascript code into a before the closing tag .
HTML:
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css">
<script src="js/Main.js"></script>
<title>Test Web App</title>
</head>
<body>
<button onclick="incrementLabel()">Test</button>
<label id="testLabel">0</label>
<script>
function incrementLabel() {
var text = document.getElementById("testLabel").textContent;
document.getElementById("testLabel").innerText = (parseInt(text) + 1);
}
</script>
</body>
Some of online tools like https://playcode.io don't recognise your code but I have tested in vscode and works fine.
Maybe have to use other online tool or can test if you have imported the code well with a console.log("Works fine") into your javascript file.
Sorry for my english.

Templete in App.vue doesn't show in index.html

I am using local vue.js These are my files.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="res/vue.js"></script>
<script src="res/vue-router.js"></script>
<title>Vue</title>
</head>
<body>
<div id="app" ></div>
<script type="module" src="App.js"></script>
</body>
</html>
App.js
import Vue from './res/vue.js'
import App from './App.vue'
Vue.config.productionTip = false
new Vue({
render: h => h(App),
}).$mount('#app')
App.vue
<template>
<div>
{{foo}}
</div>
</template>
<script>
export default {
name: 'App',
data: function(){
return{
foo:'Hello vue'
}
}
}
</script>
<style>
</style>
But my index.html shows nothing
You mount your vue instance at the div node which id is "app", but i can't find the "#app" node, so you can resolve that by insert the "#app" node .
index.html:
<body>
<div id="app"></div>
<script type="module" src="App.js"></script>
</body>
Like the Steven suggested you have to compile vue components.
If you dont want to do it that way, below is the the easiet way.
Vue.createApp({
data() {
return {
foo: 'Hello vue',
};
},
}).mount('#app');
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<script src="https://unpkg.com/vue#next"></script>
<!-- <script src="res/vue-router.js"></script> -->
<title>Vue</title>
</head>
<body>
<div id="app">{{foo}}</div>
<script type="module" src="App.js"></script>
</body>
</html>
You probably need to build it with vue-cli to create a SPA(Single page Application) for your android application
Hi is your import correct? from node_modules it should be import Vue from 'vue' and not import Vue from './res/vue.js' try it

Unable to get env variables in public/index.html for react app

Trying to get env values from public/index.html file
Tried with window.APPDYNAMICS_KEY from config.js
public/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.png" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<script src="src/config.js"></script>
<script charset='UTF-8'>
if(window.APPDYNAMICS_KEY){
....
src/config.js
export default {
STAGE: process.env.NODE_ENV || 'development',
...
APPDYNAMICS_KEY: process.env.REACT_APP_APPDYNAMICS_KEY,
};
.env
...
REACT_APP_APPDYNAMICS_KEY=SAMPLE-KEY HERE
HTTPS=true
Turns out i didn't have to import any script.
Just use the following '%REACT_APP_APPDYNAMICS_KEY%' in my index.html
public/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.png" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<script charset='UTF-8'>
if('%REACT_APP_APPDYNAMICS_KEY%'){
....
.env
...
REACT_APP_APPDYNAMICS_KEY=SAMPLE-KEY HERE
HTTPS=true

Import/export implementation using Handlebars and Node.js/Express

I am trying to implement import/export using handlebars with nodejs/express. For some reason it gives me the following error Uncaught SyntaxError: Unexpected token {
File - api.js
import { getSymbolDb, executeEnterKey } from './fetchData'
const symbolTags = document.querySelector('#symbolTags')
const requestSymbol = document.querySelector('#requestSymbol')
requestSymbol.addEventListener('click', getSymbolDb)
symbolTags.addEventListener("keyup", executeEnterKey)
document.addEventListener('DOMContentLoaded', getSymbolDb)
File - fetchData.js
export function getSymbolDb() {}
export function executeEnterKey(event) {}
HTML File
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
{{{body}}}
<script src="/JS/api.js"></script>
<script src="/JS/fetchData.js"></script>
</body>
</html>
Solution
Here you will find more information on the subject. The following code is the basic example you can start with.
File - api.mjs
import { getSymbolDb, executeEnterKey } from './fetchData.mjs'
const symbolTags = document.querySelector('#symbolTags')
const requestSymbol = document.querySelector('#requestSymbol')
requestSymbol.addEventListener('click', getSymbolDb)
symbolTags.addEventListener("keyup", executeEnterKey)
document.addEventListener('DOMContentLoaded', getSymbolDb)
File - fetchData.mjs
export function getSymbolDb() {}
export function executeEnterKey(event) {}
HTML File
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
{{{body}}}
<script type="module" src="/JS/api.mjs"></script>
<script nomodule src="fallback.js"></script>
</body>
</html>

How to display a polymer element?

I am not able to make my custom element appear.
This is the project structure:
.
This is the index.html file with my element :
<link rel="import" href="./../bower_components/polymer/polymer.html">
<link rel="import" href="./../bower_components/iron-input/iron-input.html">
<dom-module id="neito-sidebar">
<template>
<style></style>
<iron-input bind-value="{{mot}}">
<label for="test">Name : </label>
<input id="test" type="text" value="{{mot::input}}">
</iron-input>
<span>[[mot]]</span>
</template>
<script>
Polymer({is: 'neito-sidebar' });
</script>
</dom-module>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="import" href="./bower_components/polymer/polymer.html">
<script src="./bower_components/webcomponentsjs/webcomponents-lite.js"></script>
<link rel="import" href="./components/neito-sidebar.html">
<title>Polymer Element</title>
</head>
<body>
<neito-sidebar></neito-sidebar>
</body>
</html>
To open it I opened the local file with Firefox (file:///C:/...).
What am I doing wrong?
Okay guys, one of the answer is : You need to use a web server to use Polymer. You cannot access it with file:///C:/ ..., So I setup a quick nodejs Express Server just for the developpement of the element and it is working well now. Here is how I do it :
The project structure
The index.html that use my polymer custom elements :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="import" href="./bower_components/webcomponentsjs/webcomponents-lite.js">
<link rel="import" href="./elements/neito-sidebar.html">
<title>Polymer Element</title>
</head>
<body>
<neito-sidebar></neito-sidebar>
</body>
</html>
The server app.js (really ultra simple) :
var express = require('express'),
path = require('path');
const _port = 3000;
var app = express();
app.use(express.static(path.join(__dirname, '/..', 'public')))
app.get('/', function (req, res){
res.sendFile('../public/index.html', {root: __dirname});
})
.listen(_port, function (){
console.log('Server listening on : '+_port);
})
And the component definition :
<!DOCTYPE html>
<link rel="import" href="./../bower_components/polymer/polymer.html">
<dom-module id="neito-sidebar">
<template>
<style>
span
{
padding: 5px;
border: 1px solid black;
}
</style>
<label for="test">Name : </label>
<input type="text" name="test" id="test">
<button onclick="_updateSpan">Valider</button>
<span>{{mot}}</span>
</template>
<script>
Polymer({
is: 'neito-sidebar',
properties:
{
mot:
{
type: String,
notify: true
}
},
_updateSpan: function()
{
this.mot = $('#test').val();
}
});
</script>
</dom-module>
For now the updateSpan doesnt work but the element is displayed :).
So here my auto-answer, have a good day

Categories

Resources