Webpack, React & Babel, not rendering DOM - javascript

I finally after hours made my Webpack, React & Babel build setup, but when I try to just run a simple render Hello World it doesn't output anything in the DOM.
Here is my code.
var React = require('react');
var ReactDOM = require('react-dom');
ReactDOM.render(
<h1>Hello, world!</h1>,
document.getElementById('content')
);
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<script src="bundle.js"></script>
</head>
<body>
<div id="content"></div>
</body>
</html>
And when I watch my bundle.js I can see it imports all the React & ReactDOM I need to run the render.
The test I'm running is from: https://facebook.github.io/react/docs/getting-started.html.
Getting this console error: Uncaught Error: Invariant Violation: _registerComponent(...): Target container is not a DOM element.

Your bundle.js file is being loaded before the DOM has had time to load. This means that it won't be able to find your <div id="content"> when you have asked for it.
Try putting the script loader before the end of the body.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
</head>
<body>
<div id="content"></div>
<script src="bundle.js"></script>
</body>
</html>
When browsers find a <script> tag, they pause execution while they download the file. This means that your DOM has only partially rendered when your bundle.js script begins executing. So you would have essentially been passing undefined to the ReactDOM.render method.
If you have not had this issue in the past, perhaps you have been using the jQuery.ready event handler, which waits for the DOM to be loaded before executing.

bundle.js is executed when the content element isn't yet parsed an created. Just move your script element to the end of the markup.

Related

How to export variables to other javascript file

I want to use variables which is in main.js file in other js file and I tried everything ( exporting modules, declaring global variables) but nothing works and I have to do it because other js file is greatly dependent to those variables which are in main.js file.
Is there any other way to do it, if yes, please enlighten me.
Since you've stated that you're writing JavaScript code to be executed in web browsers, here's what your main.js file may look like (holding the variable importantVariable):
const importantVariable = 10;
Next, we have another JavaScript file, other.js (using the variable importantVariable):
console.log(importantVariable);
In the HTML document, where you're willing to use the scripts, include the main.js BEFORE the other.js file.
<!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">
<title>Document</title>
</head>
<body>
<script src="main.js"></script>
<script src="other.js"></script>
</body>
</html>
You should get "10" in the console, which indicates that the variable sharing of one file with other[s] worked successfully.
Explanation: A variable in the global scope should be accessible to all scripts loaded after it is declared.
We can use es modules in browsers.
index.html
<!DOCTYPE html>
<html>
<body>
<script type="module" src="./main.js"
</body>
</html
main.js
import { message } from "./other.js";
console.log(message)
other.js
export const message = "haha"
Note:
Due to the CORS policy, openning index.html directly will throw an error.
...has been blocked by CORS policy...
So you need to deploy them in an server.
Have you tried importing it into the receiving JavaScript file? This can sometimes be necessary as well as exporting it. Here's an example
In index.js:
export someVariable
In otherFIle.js: import { someVariable } from './index'

How to get rid of emscripten logo and console while only having a canvas?

Whenever I compile my C code with emcc main.c -o index.html emscripten generates an html file with their logo and some buttons and the console. But I don't want those. I only want the canvas where I can show my SDL rendered stuff.
I did a little bit of research and found this question in stack overflow. Apparently you have to enter emcc --shell-file and give it some template html as an argument.
So I made a template html file like so
<html>
<head>
<title>Some title</title>
</head>
<body>
</body>
</html>
But when I ran emcc main.c -o index.html --shell-file template.html it gave an error. Apparently emscripten looks for some think like - {{{ SCRIPT }}}.
So I added {{{ SCRIPT }}} inside my body. It compiled fine. But when I ran my index.html in localhost:3000 I got an error in the console which said cannot find addEventListener of undefined.
[N.B. I am running an SDL program. The one mentioned in their docs
What should I do? Thanks in advance
Here is a minimal example that you can use as your index.html, assuming your canvas code is in index.js:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<!-- Create the canvas that the C++ code will draw into -->
<canvas id="canvas" oncontextmenu="event.preventDefault()"></canvas>
<!-- Allow the C++ to access the canvas element -->
<script type='text/javascript'>
var Module = {
canvas: (function() { return document.getElementById('canvas'); })()
};
</script>
<!-- Add the javascript glue code (index.js) as generated by Emscripten -->
<script src="index.js"></script>
</body>
</html>

How to embed external js code into React component

I am working in a project, where I have to use a widget_api code provided by RIPE Stat, to integrate the graphical widget into a React component.
For example in HTML5, I would have done it like this, and it works fine.
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Widget</title>
</head>
<body>
<script src="https://stat.ripe.net/widgets/widget_api.js"></script>
<div class="statwdgtauto">
<script>
ripestat.init("rir-geo",{"resource":"80.12.67.0/24"},null,{"size":"500","disable":["controls"]})
</script>
</div>
</body>
</html>
While doing research I found this react-safe library which allows to do the same thing in React
Here is the code of my index file.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.png" />
<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="manifest" href="%PUBLIC_URL%/manifest.json" />
<title>MyWHOIS</title>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
</head>
<body class="bd-home">
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<script src="./js/polyfill.js" defer ></script>
<script src="https://stat.ripe.net/widgets/widget_api.js" async></script>
</body>
</html>
And the component that I created for...
import React, { Component } from 'react';
import Safe from "react-safe";
export default class EmbedComponent extends Component {
constructor(props){
super();
/*
const widget_api = document.createElement("script");
widget_api.src = "https://stat.ripe.net/widgets/widget_api.js";
widget_api.async = true;
document.body.appendChild(widget_api);
*/
}
render() {
const params1 = {"family":4,"warnings":1,"delegated":1,"resource":"FR"};
const params2 ={"resource":"127.0.0.1/24"};
const control = {"size":"500","disable":["controls"]};
return (
<div>
<h4>Include Embed</h4>
<div className="statwdgtauto">
<Safe.script>
{`ripestat.init("rpki-by-country",${params1},null,${control})`}
</Safe.script>
<Safe.script>
{`ripestat.init("rir-geo",${params2},null,${control})`}
</Safe.script>
</div>
</div>
)
}
}
I have errors, when I include the file with the tag with async or defer, I have a cors error
A parser-blocking, cross site (i.e. different eTLD+1) script, , is invoked via document.write. The network request for this script MAY be blocked by the browser in this or a future page load due to poor network connectivity. If blocked in this page load, it will be confirmed in a subsequent console message. See for more details.
And without defer or async I have this problem of writing on the document
Failed to execute 'write' on 'Document': It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened. widget_api.js:90
Define a new state isLoading
constructor(props) {
super(props);
this.state = {
isLoading: true,
};
}
componentDidMount() {
const widget_api = document.createElement("script");
widget_api.src = "https://stat.ripe.net/widgets/widget_api.js";
widget_api.async = true;
// Wait for the onload here
widget_api.script.onload = () => setState({isLoading: false})
document.body.appendChild(widget_api);
}
and on you render function do something during the isLoading phase (you can display a loader instead of your current implementation)
The issue here is that you are locked into an implementation detail of ripeStat which prevents use of it in some of the modrn frameworks, react for instance.
If you look at the ripeStat code, here for instance, https://stat.ripe.net/widgets/widget_api.js you see that it has calls to document.write.
document.write would not kick in, in a deferred situation and is expected.Check here https://developer.mozilla.org/en-US/docs/Web/API/Document/write#notes and you will find the same error that you are seeing.
Once the document has been read, parsed and closed, document.write calls will not be entertained.
I think this is a limitation of the ripeStat library. What they should use instead is
const script = document.createElement('script');
script.src = 'https://stat.ripe.net/widgets/widget_api.js';
document.head.appendChild(script);
which will ensure that it works across the board correctly.
Another option, which is probably a better one is for an npm package from ripeStat which will help the moderm frameworks.
The only way it will work correctly right now within your react application is that the script has to be present before the browser starts parsing your HTML and interpreting it.

JQuery in Laravel imported but not working

I am playing around with Laravel last version, trying to import and use JS files on the front-end. I have them stored in my folder 'public/js/'.
I have this Blade template you can see below, pizza.blade.php. If you inspect the page source, you can clearly see the JS files are existing, since their links, which are regularly working, are "http://localhost:8000/storage/...".
Nevertheless, they are not working inside the document and, inspecting the network tab, I can see they are not imported.
The image, pizza.png, located in 'public/storage' is displaying correctly.
What am i doing wrong?
Also, is there a better practice to use JS files, such as mix or npm? Thanks in advance.
<!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">
<script>src="{{asset('/js/jquery-3.3.1.js')}}"</script>
<script>src="{{ asset('/js/test.js') }}"</script>
<title>Document</title>
</head>
<body>
<h1 class="ciao">PIZZA LOGO</h1>
<div>
<img src="http://localhost:8000/storage/pizza.png" alt="">
</div>
</body>
<script>
$(document).ready(function () {
$(".ciao").css('display', 'none');
});
</script>
</html>
You have this error
<script>src="{{asset('/js/jquery-3.3.1.js')}}"</script>
this is just script with single javascript variable and string inside. You need this:
<script src="{{asset('/js/jquery-3.3.1.js')}}"></script>
this is html script tag with src attribute.

react.js chrome browser related issue

when I am typing react.js code that is given in bucky's react.js tutorial series it is not getting executed but when pasting it from bucky's github repo. it is getting executed.....Can any one help me out please...and the code is.
<html>
<head>
<title>
creating component
</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script type="text/javascript" src="C:\Users\hatim\Desktop\react\React-Boilerplate-master\src\js\react.min.js"></script>
<script type="text/javascript" src="C:\Users\hatim\Desktop\react\React-Boilerplate-master\src\js\react-dom.min.js"></script><script type="text/javascript" src="C:\Users\hatim\Desktop\react\React-Boilerplate-master\src\js\browser.min.js"></script>
</head>
<body>
<div id="container_new"></div>
<script type="text/babel" >
var mycomponent=React.createClass({
render: function(){
return(<p>this is new component </p>);
}
});
ReactDOM.render(<mycomponent />,document.getElementById('container_new'));
</script>
</body>
</html>
I don't believe you can include the JavaScript files in the context of the location on your hard drive "c:\". I think you need to be running them using a web server (IIS, Node, etc.) and then include them using relative or absolute web paths (http://localhost/mytest/src/js/react-dom.min.js).

Categories

Resources