Integrating React app into a Wicket/wro4j app [duplicate] - javascript

I just got started using React, so this is probably a very simple mistake, but here we go. My html code is very simple:
<!-- base.html -->
<html>
<head>
<title>Note Cards</title>
<script src="http://<url>/react-0.11.2.js"></script>
<!-- <script src="http://<url>/JSXTransformer-0.11.2.js"></script> -->
<script src="http://code.jquery.com/jquery-1.10.0.min.js"></script>
{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static "css/style.css" %}">
<script src="{% static "build/react.js" %}"></script>
</head>
<body>
<h1 id="content">Note Cards</h1>
<div class="gotcha"></div>
</body>
</html>
Note that I am using Django's load static files here. (My JavaScript is a bit more complex, so I won't post it all here unless someone requests it.) This is the line with the error:
React.renderComponent(
CardBox({url: "/cards/?format=json", pollInterval: 2000}),
document.getElementById("content")
);
After which I get the 'target container is not a DOM element error' yet it seems that document.getElementById("content") is almost certainly a DOM element.
I looked at this stackoverflow post, but it didn't seem to help in my situation.
Anyone have any idea why I'd be getting that error?

I figured it out!
After reading this blog post I realized that the placement of this line:
<script src="{% static "build/react.js" %}"></script>
was wrong. That line needs to be the last line in the <body> section, right before the </body> tag. Moving the line down solves the problem.
My explanation for this is that react was looking for the id in between the <head> tags, instead of in the <body> tags. Because of this it couldn't find the content id, and thus it wasn't a real DOM element.

Also make sure id set in index.html is same as the one you referring to in index.js
index.html:
<body>
<div id="root"></div>
<script src="/bundle.js"></script>
</body>
index.js:
ReactDOM.render(<App/>,document.getElementById('root'));

webpack solution
If you got this error while working in React with webpack and HMR.
You need to create template index.html and save it in src folder:
<html>
<body>
<div id="root"></div>
</body>
</html>
Now when we have template with id="root" we need to tell webpack to generate index.html which will mirror our index.html file.
To do that:
plugins: [
new HtmlWebpackPlugin({
title: "Application name",
template: './src/index.html'
})
],
template property will tell webpack how to build index.html file.

Just to give an alternative solution, because it isn't mentioned.
It's perfectly fine to use the HTML attribute defer here. So when loading the DOM, a regular <script> will load when the DOM hits the script. But if we use defer, then the DOM and the script will load in parallel. The cool thing is the script gets evaluated in the end - when the DOM has loaded (source).
<script src="{% static "build/react.js" %}" defer></script>

Also, the best practice of moving your <script></script> to the bottom of the html file fixes this too.

I had encountered the same error with React version 16. This error comes when the Javascript that tries to render the React component is included before the static parent dom element in the html. Fix is same as the accepted answer, i.e. the JavaScript should get included only after the static parent dom element has been defined in the html.

For those that implemented react js in some part of the website and encounter this issue.
Just add a condition to check if the element exist on that page before you render the react component.
<div id="element"></div>
...
const someElement = document.getElementById("element")
if(someElement) {
ReactDOM.render(<Yourcomponent />, someElement)
}

Also you can do something like that:
document.addEventListener("DOMContentLoaded", function(event) {
React.renderComponent(
CardBox({url: "/cards/?format=json", pollInterval: 2000}),
document.getElementById("content")
);
})
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.

One of the case I encountered the same error in a simple project. I hope the solution helps someone.
Below code snippets are sufficient to understand the solution :
index.html
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
someFile.js : Notice the line const portalElement = document.getElementById("overlays"); below :
const portalElement = document.getElementById("overlays");
const Modal = (props) => {
return (
<Fragment>
      {ReactDOM.createPortal(<Backdrop />, portalElement)}
      
{ReactDOM.createPortal(
<ModalOverlay>{props.children}</ModalOverlay>,
portalElement
)}
    
</Fragment>
);
};
I didn't have any element with id = "overlays" in my index.html file, so the highlighted line above was outputting null and so React wasn't able to find inside which element it should create the portal i.e {ReactDOM.createPortal(<Backdrop />, portalElement)} so I got below error
I added the div in index.html file and the error was gone.
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="overlays"></div>
<div id="root"></div>
</body>

I got the same error i created the app with create-react-app but in /public/index.html also added matrialize script but there was to connection with "root" so i added
<div id="root"></div>
just before
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/ materialize.min.js"></script>
And it worked for me .

Target container is not a DOM element.
I achieved this error with a simple starter app also.
// index.js
ReactDOM.render(
<Router>
<App />,
document.getElementById('root')
</Router>
);
Solution:
Syntax errors can cause this error. I checked my syntax and wrapped my <App /> properly.
ReactDOM.render(
<Router>
<App />
</Router>,
document.getElementById('root')
);

In my case, I forget to add this line to the index.js file
document.getElementById('root')
and I forget to import react-dom import ReactDOM from 'react-dom'; so you can use ReactDOM later in the same file
Hope this will be helpful for you

Related

How to get another component on ReactJs use ES6 modules

i need help for integrate frontend ReactJS on my site. currently i avoid to use nodeJS or NPM for implement my reactJS. but i'm using ReactJS CDN. so i not run npm start when develop the reactJS. i just want to use the frontend.
Hope this will understand from the start. so i have a question, how do i able to get another component and place it on single file.
I Created file App.js. I plan that this file will become a centralize for other components.
let me share what i'm doing right now.
here is my file structure
this is my code on index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Buynow Project</title>
<script src="https://unpkg.com/react#16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom#16/umd/react-dom.development.js" crossorigin></script>
<script src="https://unpkg.com/babel-standalone#6/babel.min.js"></script>
<script type="text/babel" src="buynow/index.js"></script>
</head>
<body>
<div id="root"></div>
</body>
</html>
this is my code on index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.js'
ReactDOM.render(<App />, document.getElementById('root'));
this is my code on App.js
import React from 'react';
import Navbar from './components/Navbar.js'
function App(props){
return (
<div>
<Navbar/>
Hello App
</div>
);
}
export default App;
this is my code on Navbar.js
import React from 'react';
function NavBar(props) {
return (
<div>
<Navbar/>
Hi NavBar
</div>
);
}
export default NavBar;
but i got this error, and pointed on file index.js line:1
Uncaught ReferenceError: require is not defined
this is error
I confuse how to solve this. I start with the simple code just for testing if it can work or not.
please help.
https://reactjs.org/docs/react-without-jsx.html
JSX is not a requirement for using React. Using React without JSX is
especially convenient when you don’t want to set up compilation in
your build environment.
So you can't use JSX/TSX directly in your browser (need compilation). Also, you can't use import outside a module (so basically now, you can already use your function components by adding the import of all your files in the index.html).
In my experience I suggest that you use the benefits of JSX / TSX and compile your code with NPM to be more comfortable (everything is way more intuitive with jsx).
In any case, in the link that I have included, you will find how to do the equivalent of JSX with pure javascript. That's what you need. (as you can see in my small snippet)
If you want keep using react from CDN and without compiling, your code, should be something like this:
// For the Snippet i have all of your js here
// But you could just import in your index.html every separate component file you have (without any import/export syntax)
function NavBar(props) {
return React.createElement('span', null,props.title);
}
function App(props){
return React.createElement('span', null, React.createElement(NavBar, {title: 'Header'}, null),
React.createElement('span', null,'Hello App'));
}
ReactDOM.render(React.createElement(App, {}, null), document.getElementById('root'));
<html>
<head>
<meta charset="UTF-8" />
<title>Buynow Project</title>
<script src="https://unpkg.com/react#16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom#16/umd/react-dom.development.js" crossorigin></script>
<script src="https://unpkg.com/babel-standalone#6/babel.min.js"></script>
</head>
<body>
<div id="root"></div>
</body>
</html>
Anyway, as you see, the code is not so readable this way...
EDIT
I made the same snippet on stackblitz with separated files
https://stackblitz.com/edit/web-platform-4ruju9?file=index.html
Ps. Also, don't put NavBar inside NavBar or you'll get a render loop
You have to enable module support in script tag
<script type="text/babel" data-type="module" src="./index.js"></script>
Remove React import statements as they can be directly used.

Why are External JS files added in html file not working when using react-router-dom

I am currently working on a react application and everything was working fine until recently when I noticed that all the external scripts I defined in the public/html no longer works when rendering pages using react-router-dom, but works fine when I call the pages directly.
These is my html file body tag:
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<script
defer
type="text/javascript"
src="%PUBLIC_URL%/assets/js/plugins.bundle.js"
></script>
<script
defer
type="text/javascript"
src="%PUBLIC_URL%/assets/js/scripts.bundle.js"
></script>
<script
defer
type="text/javascript"
src="%PUBLIC_URL%/assets/js/intro.js"
></script>
<script
defer
type="text/javascript"
src="%PUBLIC_URL%/assets/js/widgets.js"
></script>
<script
defer
type="text/javascript"
src="%PUBLIC_URL%/assets/js/chat.js"
></script>
<script
defer
type="text/javascript"
src="%PUBLIC_URL%/assets/js/modals/create-app.js"
></script>
</body>
Everthing works perfectly if I render the page this way:
const App = () => {
return (
<UserDashboard/>
);
};
export default App;
But when using react-router-dom, it doesnt throw any errors but nothing works
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<UserDashboard />/>
<Route path="/login" element={<Login />} />
</Routes>
</BrowserRouter>
);
My folder structure
Please does anyone know why this is happening and how can I fix it, cause I'm using a template and those scripts are necessary for the template to function properly.
I'm beginning to think this has to with react-router-dom version 6, cause I have not encountered this problem when working on previous projects. Its the only thing I can suspect would downgrading the react-router-dom be a bad idea?
I had a similar issue where I needed to load scripts in html tags in an app created from create-react-app library and found that I needed to put them in the body, afer rootand use the deferkeyword as below:
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<script defer type='text/javascript' src='%PUBLIC_URL%/ccapture/CCapture.js'></script>
<script defer type='text/javascript' src='%PUBLIC_URL%/ccapture/gif.js'></script>
<script defer type='text/javascript' src='%PUBLIC_URL%/ccapture/webm-writer-0.3.0.js'></script>
<script defer type='text/javascript' src='%PUBLIC_URL%/ccapture/download.js'></script>
Can't remember if using the %PUBLIC_URL% variable was part of the solution or I just used it because the template had similar.
The script paths are relative to the current URL path. They probably work without issue if/when the app loads and you are on the root "/" route, but have issue when on any sub-route.
Specify absolute paths in your public directory instead.
<script src="/assets/js/plugins.bundle.js"></script>
<script src="/assets/js/scripts.bundle.js"></script>
<script src="/assets/js/intro.js"></script>
<script src="/assets/js/widgets.js"></script>
<script src="/assets/js/chat.js"></script>
<script src="/assets/js/modals/create-app.js"></script>
I had a similar issue. I'm using Electron with webpack and was able to resolve this by adding a custom file protocol to handle custom requests for static files. Added within the window creation handler. This may be of help.
import { app, BrowserWindow, session } from 'electron';
//...
session.defaultSession.protocol.registerFileProtocol('asset', (request, callback) => {
const fileUrl = request.url.replace('asset://', '');
const filePath = path.join(app.getAppPath(), '.webpack/assets', fileUrl);
callback(filePath);
});

PWA Simple Demo - Error when add pwabuilder-sw-register.js

Hello,
I'm trying to create a simple PWA demo by following the steps of this article: "https://learn.microsoft.com/en-us/microsoft-edge/progressive-web-apps-chromium/get-started"
However when I reach the step to download and add the files: "pwabuilder-sw.js" and "pwabuilder-sw-register.js" to root and then add <script src="/pwabuilder-sw-register.js"></script> to the head of index.html I got error on Edge browser: "SCRIPT1086: SCRIPT1086: Module import or export statement unexpected here" I search around and I find that I have to add type="module" like this <script src="/pwabuilder-sw-register.js" type="module"></script> but now I'm getting another error: "0: Unable to get property 'define' of undefined or null reference" in
pwaupdate (175,5829)
My page code looks like:
Index.html
<html>
<head>
<title>Express</title>
<link rel="stylesheet" href="/stylesheets/style.css">
<link rel="manifest" href="/manifest.json">
<script src="/pwabuilder-sw-register.js" type="module"></script>
</head>
<body>
<h1>Express 2</h1>
<p>Welcome to Express</p>
</body>
</html>
pwabuilder-sw.js
// This is the service worker with the Cache-first network
const CACHE = "pwabuilder-precache";
importScripts('https://storage.googleapis.com/workbox-cdn/releases/5.0.0/workbox-sw.js');
self.addEventListener("message", (event) => {
if (event.data && event.data.type === "SKIP_WAITING") {
self.skipWaiting();
}
});
workbox.routing.registerRoute(
new RegExp('/*'),
new workbox.strategies.CacheFirst({
cacheName: CACHE
})
);
pwabuilder-sw-register.js
// This is the service worker with the Cache-first network
// Add this below content to your HTML page inside a <script type="module"></script> tag, or add the js file to your page at the very top to register service worker
import 'https://cdn.jsdelivr.net/npm/#pwabuilder/pwaupdate';
const el = document.createElement('pwa-update');
document.body.appendChild(el);
I searched a lot but I did not find any clue.
Please advise.
There are only 2 things you need to make this work:
Add pwabuilder-sw.js and pwabuilder-sw-register.js to your site root.
Add the following script tag to your <head>
<script type="module" src="pwabuilder-sw-register.js"></script>
Here's a quick sample that shows this working.
It looks like the MSDN article missed the "module" script type. My fault! I've updated the MSDN article to include this fix.
You normally don't need any more this script reference <script src="/pwabuilder-sw-register.js" type="module"></script>
The script will be loaded by the pwaupdate component. So simply add this code inside a block at the end of your HTML page:
import 'https://cdn.jsdelivr.net/npm/#pwabuilder/pwaupdate';
const el = document.createElement('pwa-update');
document.body.appendChild(el);
If it still doesn't work, please open an issue on our Github repo or ask to Justin who's in charge of this part on Twitter: https://twitter.com/Justinwillis96
Thanks!
David

Spring Boot (inject script in reactjs)

I'm having a really difficult time figuring out what I possibly could do wrong as probably most scenarios has been tested.
I'm writing web app using Spring Boot and ReactJS for frontend. I'm trying for now to write simple script showing some plain text which is imported from separate file to html one. After doing so, I ended up with nothing really showing up.
Here is my structure of project:
and here is my app.js in which I have my component defined:
var CommentBox = React.createClass({
render: function() {
return (
<div className="commentBox">
Hello, world! I am a CommentBox.
</div>
);
}
});
ReactDOM.render(<CommentBox />, document.getElementById('content')
);
Below is the cardists.html page:
<!DOCTYPE html>
<html>
<head>
<title>Cardists</title>
<link rel="stylesheet"href="https://maxcdn.bootstrapcdn.com/bootstrap/
3.3.7/css/bootstrap.min.css"/>
</head>
<body>
<div id='root'></div>
<script src="react-15.0.1.js"></script>
<script src="react-dom-15.0.1.js"></script>
<script src="cdnjs.cloudflare.com/ajax/libs/babel-
core/5.8.23/browser.min.js"></script>
<script type="text/babel" src="../public/js/app.js"></script>
</body>
</html>
[PROBLEM]
Where could I possibly made a mistake as everything for first glance seems ok to me, but I'm getting blank page ;/
You are rendering your application in content div like
ReactDOM.render(<CommentBox />, document.getElementById('content')
But in you html file there is no div with content id. There is one div with id root so you need to render your component in that div like
ReactDOM.render(<CommentBox />, document.getElementById('root')

Loading JSX file from content server asp.net

I am facing a issue when I am trying to get my JSX file by a content server. The application has a view Test.cshtml and in this calls a jsx file to render the react portion of the UI to the 'content' div.
When I run it locally in the project using the file structure from the solution it works fine.
<div id="content">
#*react renders here*#
</div>`
#section Scripts{
<script src="_linktoReact_/react-0.14.0.js"></script>
<script src="_linktoReact_/react-dom-0.14.0.js"></script>
<script src="~/Scripts/JSX/test.jsx">
</script>
}
But when I try to run from content server to host the files in a central location (which in this case is localhost:8111) it does not work. The file loads into the browser, but the jsx doesnt execute. This will give me an error of "Uncaught SyntaxError: Unexpected token <" which points to the first line of HTML in the jsx file.
<div id="content">
#*react renders here*#
</div>`
#section Scripts{
<script src="_linktoReact_/react-0.14.0.js"></script>
<script src="_linktoReact_/react-dom-0.14.0.js"></script>
<script src="http://localhost:8111/Scripts/JSX/test.jsx">
</script>
}
So I tried adding the type tag to reference jsx, like below. This removed the "uncaught syntax error" but then doesn't give any errors but also doesn't render the react.
<div id="content">
#*react renders here*#
</div>`
#section Scripts{
<script src="_linktoReact_/react-0.14.0.js"></script>
<script src="_linktoReact_/react-dom-0.14.0.js"></script>
<script type="text/jsx" src="http://localhost:8111/Scripts/JSX/test.jsx">
</script>
}
I tried to find the problem a few different ways and have tinkered with solutions around scoping, CORS, maybe even an issue with routing on the server, but not sure what fixes it.
Attempts to fix:
One suggestion was to use window instead of var like
var TestDataTile = React.createClass({
replace with
window.TestDataTile = React.createClass({
But that to is not working. I am using react-0.14.0.js, react-dom-0.14.0.js
Tried to recompile into js file, which rendered as expected in the solution, but still some issues with some of the code in the test.js file in regard to some api calls.
What could be causing the jsx disconnect?
Can anyone guide me towards correct direction?

Categories

Resources