Introducing redux in existing web application (JSP) with ReactJS - javascript

I'm migrating a web application Java/jsp to a reactjs.
The pages are built with jsp templates, which compose the final HTML.
So I cannot use (yet) Reactjs to render my entire application, but just for render some component into the DOM.
So I have a mixed rendering, like this
<html>
</html>
<body>
<header></header> <!-- JSP code -->
<div id="myComponent"></div> <!-- this is rendered by react -->
<article></article> <!-- JSP code -->
<div id="myOtherComponent"></div> <!-- this is rendered by react -->
<footer></footer> <!-- JSP code -->
</body>
Everyhting works fine so far, so I'm trying to introduce Redux to handle the state, but I got stucked when I should render the <Provider /> component as the docs says, since I don't have an entry point for my application.
So I tried adding one, wrapping all my app code into a div:
<html></html>
<body>
<div id="app">
<header></header>
<!-- etc... -->
</div>
</body>
And then in my index.js
render(
<Provider store={store}>
<div />
</Provider>,
window.document.getElementById('app')
);
But of course it doesn't work, all my page is blank now, and the block <div id="app"> is empty
Does this Provider element must include all my components in order to work? Can I use Redux with this mixed setup?
I'm kind of lost, any help would be great.

The Provider component should wrap all the components that will use your Redux store via connect(). Redux documentation recommends just wrapping all components in Provider because there is no problem since you're just using a single store.
In React you shouldn't need to ever put elements directly in the body because this is done dynamically.
Here is an example of what your main application files should look like:
index.html
<!doctype html>
<html lang="en">
<head>
... some scripts/css...
</head>
<body>
<div id="root">
// intentionally nothing here. will be dynamically inserted via React later
</div>
</body>
</html>
entry.tsx:
ReactDOM.render(
<Provider store={store}>
<header></header> <!-- JSP code -->
<div id="myComponent"></div> <!-- this is rendered by react -->
<article></article> <!-- JSP code -->
<div id="myOtherComponent"></div> <!-- this is rendered by react -->
<footer></footer>
</Provider>,
document.getElementById('root')
);
To make an entry point simply add the following to your webpack config file:
module.exports = {
entry: './entry.tsx',
...
}
This is the barebones of a React-Redux application that you should follow when you are ready to transition.

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.

Katex auto rendering not working in a Vue project

I'm trying to implement this Katex auto-rendering extension: https://katex.org/docs/autorender.html, it looks for specific delimiters to find katex strings and renders them in the HTML.
I've followed the instructions and added the CDN to the header of my index.html like so:
<!-- KATEX AUTO RENDERING -->
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/katex#0.12.0/dist/katex.min.css"
integrity="sha384-AfEj0r4/OFrOo5t7NnNe46zW/tFgW6x/bCJG8FqQCEo3+Aro6EYUG4+cU+KJWu/X"
crossorigin="anonymous"
/>
<script type="module">
import renderMathInElement from "https://cdn.jsdelivr.net/npm/katex#0.12.0/dist/contrib/auto-render.mjs";
renderMathInElement(document.body);
</script>
As a test, I put the following in my <body> tag of my index.html:
<body>
<div>
<div>
The formula $a^2+b^2=c^2$ will be rendered inline, but $$a^2+b^2=c^2$$
will be rendered as a block element.
</div>
<br />
<div>
The formula \(a^2+b^2=c^2\) will be rendered inline, but \[a^2+b^2=c^2\]
will be rendered as a block element.
</div>
</div>
<div id="app"></div>
</body>
It works perfectly, I can see the katex rendered on the screen.
But now I want to add these types of katex formula strings in my other Vue components. I put the exact same formula div in my Home.vue component's template:
<template>
<div>
<app-header></app-header>
<div>
<div>
The formula $a^2+b^2=c^2$ will be rendered inline, but $$a^2+b^2=c^2$$
will be rendered as a block element.
</div>
<br />
<div>
The formula \(a^2+b^2=c^2\) will be rendered inline, but \[a^2+b^2=c^2\]
will be rendered as a block element.
</div>
</div>
<textbook-selection></textbook-selection>
<app-footer></app-footer>
</div>
</template>
But the katex is not rendered. Why does this happen?
I'm using Vue v2.6.11 with Katex v0.12.0, with vue-cli, vue-router, babel, if those are of any relevance.

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

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

Multiple Vue instances bind to parent & child elements

I would like to ask for best setup of Vue instances (components), when I do not want use SPA.
My HTML looks like:
<html>
<div id="layout">
<div>Some Layout based content...</div>
<div id="homepage">
<simple-form-component></simple-form-component>
</div>
</div>
<script type=text/javascript src="homepage.js"></script>
<script type=text/javascript src="layout.js"></script>
</html>
Currently I have simple example ot two .js files:
layout.js
homepage.js
// layout.js
import Vue from 'vue/dist/vue.js'
new Vue({
el: '#layout',
});
// homepage.js
import Vue from 'vue/dist/vue.js';
import SimpleForm from '../../../../components/SimpleForm.vue';
new Vue({
el: '#homepage',
components: {
SimpleForm,
},
});
It seems to work fine, but I am suspicious that this is not 100% correct, due to console error:
[Vue warn]: Unknown custom element: - did you register
the component correctly? For recursive components, make sure to
provide the "name" option.
(found in )
Do you have any ideas/experience how to setup my scenario correctly?
PS: I would like to have my JS split into different files, managed by webpack and distributed by backend.
Thank you,
Mario
I've found workaround v-pre, my HTML will change the line: <div id="homepage" v-pre>. One small issue is, that I will not see my components in Vue Devtools.

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')

Categories

Resources