Use React to build parts of the application features - node.js

Consider having a web application that is based on a complex platform, however, you can design HTML Forms using its designer, and insert standard HTML elements, one of which is HTML Component. You can use this component to add HTLM/JavaScript code as usual.
I followed a tutorial to create a react app without using create-react-app. I managed to develop a sample React app using NodeJs, Babel, and Webpack and managed to deploy the final bundled JavaScript main.js on the target application. All worked fine. Below are the main two files with the source code:
index.js
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
ReactDOM.render(<App />, document.querySelector("#root"));
App.js
import React, {useState} from "react";
const App = () => {
let [counter, setCounter] = useState(0);
const increment = () => {
counter++;
setCounter(counter);
}
return <div>This was created from React and Hello World!
<h1>This is a test Header</h1>
<button onClick={increment}>Click here to increment</button>
<br/>
<span>{counter}</span>
</div>
}
export default App;
The Form HTML Component in the Target Web Application:
<div id="root">This Text should be replaced by the React App</div>
<script src="./target/app/path/public/main.js"></script>
Mind you that I ran the command npm run build and it generated the final script main.js which is deployed to the target application.
I am planning to start using React to build specific components for example a combination of Drop-Down Fields and Grid elements which are populated using REST APIs.
The problem is that I have to have one entry JavaScript source file that will render the component using ReactDOM.render(<App />, document.querySelector("#root")), and if I develop say 100 components, but not all of them will be rendered when any Application Form is loaded. I think if the React render() function is invoked and the target DOM element is not present, then it will throw an error (I am not sure though).
So the question is how to design the application so that I can follow the above approach and ensure that the intended React Component will kick in only when the related Form is loaded or active.
I am thinking to import all the Components in index.js and develop a method to detect if the Form is active and needs a component, then it will invoke the function ReactDOM.render(<MyComponent />, document.querySelector("#MyComponentId")).
I am not sure how to implement that and I need help. I appreciate your feedback.

Related

How to do Jest testing in Node app with added React components

We have a Node app that we're going to rewrite in React next year so we're building all of our new .jsx components in React and injecting them into ReactDOM like they describe here: https://reactjs.org/docs/add-react-to-a-website.html
We build the .jsx React components with Babel/webpack before we deploy the site and this works pretty well.
But now I'm trying to write Jest tests for these components and I'm getting an error when I import the React component file into my test:
createRoot(...): Target container is not a DOM element.
How do I get my test to see the container as a DOM element? I've tried using happy-dom and jsdom but they don't see the document object.

How to ssr Svelte and pass data from express in node js

I am trying svelte and I might use it for my future website, but there is on thing that has stopped me from suing many js frameworks/compilers. It is server side rendering (one reason is I use server-less so it would be easier then prerendering). Is there a way to use express to server-side-render svelte on every request and also pass data from my node js app too so I don't have to make a bunch of other request? For example the App.svelte might be:
<script>
export let data
let count = 0
</script>
<main>
<button on:click={count++}>Increase Count BY 1</button>
<h1>{data}<h1>
</main>
and main.js:
import App from './App.svelte';
const app = new App({
target: document.body,
props: {
}
});
export default app;
I want to get the data value from the server and use it in the svelte code and also sever-side-render it. Is there a way I can do this?

react js c'ant fetch from database - node js api server keeps loading

Hi guys i'am new in react js and node.js. So , I have a problem with fetching users list from database with node rest api
so at first this screen appears without displaying users list
then i had this error that i can't gues where the problem is !
help please
ps* excuse me for the captures i had problem with code publication
here is my userlist.js and app.js code
you are importing some components from react package at your UserList:
import { Button, ButtonGroup, Table } from 'react';
These components are going to be undefined since React doesn't have built-in components. These components import should come from another library or from the specific file if you've created them.
since you are using bootstrap you should import as:
import { Button, ButtonGroup, Table } from 'react-bootstrap';

How does serving different pages in React works?

Let's say I have a react projects, and an Express server for serving my project, as follows(After building the project):
]
This way, only the index.html is served, isn't it? If the user routes to a different page, how is that page sent to him?
Routing in javascript is managed by using HTML5 push state. So every time you click a link and go to another route, the browser history and push state is being used. That's the basis for routing in almost of all the single page applications.
Until and unless you refresh the page, your request doesn't go to the server. Hence, index.html is served only once and after that the router (here the react-router) takes over and manages the routing in url using the history API of the browser.
Hope this helps !
That is done using react-router which manages the routing using the browser's History API.
This style of a website is called a single page application as opposed to a multi page application where the server sends different pages depending on the url you route to.
you can use react-router-dom like this
<Switch>
<Route exact path="/" component={Home}/>
<Route path="/someurl" component={ComponentForSomeUrl}
</Switch>
and render it with BrowserRouter
but you can use something like history.push, in my opinion react-router-dom is really simple and better than react-router
you don't need to send html file to specific route, in case of react express is used for building API (in most cases)
In you React folder you want to do npm install --save react-router-dom.
So inside the React Router family of libraries, there is a couple of different dependencies you can possibly install.
Ensure you never install React Router by itself.
The react-router library as it is published on npm is the core library of everything inside the React Router general project.
So react-router has some core navigational logic inside of it. It decides how to work with React, how to change content out depending on different rules and some other low-level logic.
To gain some actual implementation as it works specifically in the browser, install react-router-dom.
So anytime you want to use React Router on a project to handle navigation, always install react-router-dom, not react-router.
There are other similarly named projects that you might think you need as well, react-router-native for use inside of React Native projects.
In web applications we make use of react-router-dom, we are not making native mobile apps.
React-router-native is for native mobile applications only.
For the browser you always want react-router-dom as opposed to react-router-native
So perhaps in your App.js component you want to set something up that looks like this:
import React from "react";
import { BrowserRouter, Route } from “react-router-dom”;
const App = () => {
return <div>App</div>;
};
export default App;
I also recommend if you are new to React Router to get familiar with it by setting up something temporary like so:
import React from "react";
import { BrowserRouter, Route } from “react-router-dom”;
const PageOne = () => {
return <div>PageOne</div>;
};
const PageTwo = () => {
return <div>PageTwo<button>Click Me</button></div>;
};
const App = () => {
return (
<div>
<BrowserRouter>
<div>
<Route path=“/” exact component={PageOne} />
<Route path=“/pagetwo” component={PageTwo} />
</div>
</BrowserRouter>
</div>
);
};
Visit your localhost:3000 and then your localhost:3000/pagetwo, check out how all that is working.
When we visit a page called localhost:3000 and we type that address into the url it loads up the application.
React Router itself does not care about that entire url, instead React Router only cares about all the characters that are listed after the domain name or port definition.
Localhost:3000 is interpreted as being localhost:3000/
If I go to localhost:3000/ it still loads up my application.
Now I have other examples here if I go to localhost:3000/pageone, React Router only cares about everything after the port and domain
Same thing if I went to airbnb.com/listings/spain react router would only consider /listings/spain when deciding what content to render to the screen.
Notice in the example above I created an instance of BrowserRouter, well BrowserRouter creates an object of its own known as the history object.
This history object is going to look at the URL inside the address bar and extract just that portion of the URL that react router cares about.
The history object is then going to communicate that path over to BrowserRouter who communicates that path to both Route components and those Route components decide whether to show themselves or hide themselves depending on the path that the user is visiting and the path property that it was passed when it was created.

ComponentDidMount() in Server-side render

I'm trying to server-side render my webpage for better performance but am running into an issue where my page's components componentDidMount()s aren't getting called.
For example, this is my main template file:
import React from 'react';
import Cube from './components/Cube/Cube.jsx';
class Index extends React.Component {
render() {
return (
<html>
<head>
<title>{this.props.title}</title>
</head>
<body>
<Cube />
</body>
</html>
);
}
}
And my Cube.jsx:
import React from 'react';
class Cube extends React.Component {
componentDidMount() {
console.log("Hey!");
}
render() {
return (
<div>
<h1>Hello</h1>
</div>
);
}
}
export default Cube;
I'm not seeing "Hey!" getting logged out in my pm2 logs nor in my chrome console even though I'm seeing the <h1>Hello</h1> when the page loads. This is stopping me from having any sort of logic for my component.
How do I get around this problem and make my subcomponents's componentDidMount() get called? Note I'm using express-react-views for my server-side rendering.
I think the only lifecycle hook that will be called server side is componentWillMount as explained here
Even then you would not see output on Chrome's console. You are only likely to see it in your node logs.
Let me know if this answers your question.
Problem is as I my self found out few days ago using Next.js that React application is not mounted. What that means is that Server Side Rendering is exactly that. React app is 'rendered' aka static HTML file is created on the server, and served to the browser. But in that process React is not mounted and no hooks are fired. Maybe componentWillMount I am not sure and have not tested.

Resources