Fs 5
Fs 5
Fs 5
REACT
SYLLABUS:
MERN STACK – Basic React applications – React
Components – React State – Express REST APIs -
Modularization and Webpack - Routing with React
Router – Server-side rendering
MERN Stack
What is MERN Stack?
MERN Stack is a collection of powerful technologies and robust,
used to develop scalable master web applications
comprising backend, front-end, and database components. It is
JavaScript that is used for the faster and easier development of full-
stack web applications. MERN Stack is a technology that is a user-
friendly full-stack JavaScript framework for building applications and
dynamic websites.
MERN Stack consists of four main components or can say four main
technologies:
1. M stands for MongoDB ( Database ), mainly used for
preparing document database and is a NoSQL (Non-Structured
Query Language ) Database System
2. E stands for Express, mainly used for developing Node.js web
framework
3. R stands for React, mainly used for developing a client-side
JavaScript framework
4. N stands for js, mainly used for developing the premier
JavaScript web server
Each of these four technologies plays an important role in providing
an end-to-end framework for the developers. Even these four
technologies play an important role in the development process of
web applications.
Before MERN stack, it was earlier named as MEAN stack, MERN
Stack is one of the variations of MEAN, here MEAN is also
comprises of four components or say four different technologies, i.e.,
M is for MongoDB, ' E ' is for Express, ' A ' is for Angular.js, and ' N '
is for Node, here if you will observe, then you can identify that in
MEAN, ' A ', i.e., Angular.js is replaced by ' R ', i.e., React.js in
MERN, the main reason behind is - MERN Stack is mainly used for
faster development of smaller applications as compared with MEAN,
MEAN stack is a mainly better option for large-scale applications.
Still, it takes more time for the development of smaller applications.
They also both have different structures comparatively.
We can see that MEAN relies on Angular.js for its front-end
JavaScript framework, whereas the MERN stack relies
on React and its ecosystem. MERN Stack is designed to make the
development process easier and smoother.
From the above figure, if we notice, then we can see that Node and
Express make up the middle application or tier. Node.js very powerful
and popular JavaScript server platform, and Express.js is a server-side
web framework. Unless of which variant you choose, ME(RVA)N is
an ideal approach to working with JSON and JavaScript all the way
through.
Why should we choose MERN Stack for building
Mobile and Web applications?
• Make sure you have a code editor for working on your project files.
Step 2: Once it is done change your directory to the newly created application
using the following command
cd foldername
Project Structure: It is created as shown below.
Step 3: Now inside App.js and write down the following code as shown below:
import React from 'react';
import './App.css';
function App() {
return (
);
}
export default App;
Step to run the application: Enter the following command to run the
application.
npm start
ReactJS Components
What is a ReactJS Component?
A Component is one of the core building blocks of React. In other words, we
can say that every application you will develop in React will be made up of
pieces called components. Components make the task of building UIs much
easier. You can see a UI broken down into multiple individual pieces called
components and work on them independently and merge them all in a parent
component which will be your final UI.
Components in React basically return a piece of JSX code that tells what should
be rendered on the screen.
Types of components in ReactJS
In React, we mainly have two types of components:
Functional Components:
Functional components are simply javascript functions. We can create a
functional component in React by writing a javascript function. These functions
may or may not receive data as parameters, we will discuss this later in the
tutorial. The below example shows a valid functional component in React:
function demoComponent() {
return (<h1>
Welcome Message!
</h1>);
}
Class Components:
The class components are a little more complex than the functional components.
The functional components are not aware of the other components in your
program whereas the class components can work with each other. We can pass
data from one class component to another class component. We can use
JavaScript ES6 classes to create class-based components in React. The below
example shows a valid class-based component in React:
class Democomponent extends React.Component {
render() {
return <h1>Welcome Message!</h1>;
}
}
The components we created in the above two examples are equivalent, and we
also have stated the basic difference between a functional component and a
class component. We will learn about more properties of class-based
components in further tutorials.
For now, keep in mind that we will use functional components only when we
are sure that our component does not require interacting or work with any other
component. That is, these components do not require data from other
components however we can compose multiple functional components under a
single functional component.
We can also use class-based components for this purpose but it is not
recommended as using class-based components without need will make your
application in-efficient.
ReactDOM.render(
<Welcome />,
document.getElementById("root")
);
Output:
When you click the Read More button, you will get the below output, and
when you click the Show Less button, you will get the output as shown in the
above image.
Let us now create this API in Express. We will be using JSON as our transport
data format as it is easy to work with in JavaScript and has other benefits.
var express = require('express');
var bodyParser = require('body-parser');
var multer = require('multer');
var upload = multer();
app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(upload.array());
app.listen(3000);
Now that we have our application set up, let us concentrate on creating the API.
Start by setting up the movies.js file. We are not using a database to store the
movies but are storing them in memory; so every time the server restarts, the
movies added by us will vanish. This can easily be mimicked using a database
or a file (using node fs module).
Once you import Express then, create a Router and export it
using module.exports −
var express = require('express');
var router = express.Router();
var movies = [
{id: 101, name: "Fight Club", year: 1999, rating: 8.1},
{id: 102, name: "Inception", year: 2010, rating: 8.7},
{id: 103, name: "The Dark Knight", year: 2008, rating: 9},
{id: 104, name: "12 Angry Men", year: 1957, rating: 8.9}
];
res.status(400);
res.json({message: "Bad Request"});
} else {
var newId = movies[movies.length-1].id+1;
movies.push({
id: newId,
name: req.body.name,
year: req.body.year,
rating: req.body.rating
});
res.json({message: "New movie created.", location: "/movies/" + newId});
}
});
This will create a new movie and store it in the movies variable. To check this
route, enter the following code in your terminal −
curl -X POST --data "name = Toy%20story&year = 1995&rating = 8.5"
http://localhost:3000/movies
The following response will be displayed −
{"message":"New movie created.","location":"/movies/105"}
To test if this was added to the movies object, Run the get request
for /movies/105 again. The following response will be displayed −
{"id":105,"name":"Toy story","year":"1995","rating":"8.5"}
Modularization in React
Modularization in React involves breaking down your application into smaller, self-contained
pieces or modules. Each module typically corresponds to a single component, function, or
feature. Here's why modularization is crucial in React:
Benefits of Modularization
Reusability: Modules can be reused across different parts of your application or even in
different projects, saving development time and effort.
Maintainability: Smaller, well-defined modules are easier to maintain and debug than large
monolithic codebases.
Scalability: As your application grows, modularization allows you to add or update features
with minimal disruption to the existing codebase.
Webpack in React
Webpack is a popular JavaScript module bundler that plays a significant role in
modularization and optimizing React applications.
Bundling: Webpack takes your modularized code and bundles it into a single or multiple
files, reducing the number of HTTP requests and improving loading times.
Code Transformation: Webpack can transpile modern JavaScript (e.g., ES6/ES7) and JSX
into a format that older browsers can understand.
Optimization: It optimizes assets, such as minifying JavaScript and CSS, to reduce the
overall bundle size and improve performance.
Hot Module Replacement (HMR): Webpack Dev Server provides HMR, allowing you to
see real-time updates during development without refreshing the page.
Development Server: Set up a development server using Webpack Dev Server for easy
testing and development.
Loaders: Configure loaders to process different file types, such as JSX, CSS, and images.
For example, you might use Babel for JavaScript/JSX and CSS loaders for styles.
Code splitting is a technique to optimize your React application further. It involves breaking
your bundle into smaller chunks, which are loaded only when needed. This can significantly
improve your application's initial load time.
Route-Based Splitting: Split your code based on different routes in your application. Each
route can have its bundle, ensuring that users only download code related to their current
route.
ROUTING WITH REACT ROUTER
Routing is a process in which a user is directed to different pages based on their action or
request. ReactJS Router is mainly used for developing Single Page Web Applications. React
Router is used to define multiple routes in the application. When a user types a specific URL
into the browser, and if this URL path matches any 'route' inside the router file, the user will
be redirected to that particular route.
React Router is a standard library system built on top of the React and used to create routing
in the React application using React Router Package. It provides the synchronous URL on the
browser with data that will be displayed on the web page. It maintains the standard structure
and behavior of the application and mainly used for developing single page web applications.
Need of React Router
React Router plays an important role to display multiple views in a single page application.
Without React Router, it is not possible to display multiple views in React applications. Most
of the social media websites like Facebook, Instagram uses React Router for rendering
multiple views.
Step-4: In the above screen, you can see that Home component is still rendered. It is because
the home path is '/' and about path is '/about', so you can observe that slash is common in
both paths which render both components. To stop this behavior, you need to use
the exact prop. It can be seen in the below example.
Index.js
Install Next.js:
Install Next.js in your project:
- pages/
- index.js
The pages directory is where you create your routes. In this example, we have a single route
for the homepage.
app.prepare().then(() => {
const server = express();
server.listen(3000, () => {
console.log('Server is running on port 3000');
});
});
Your SSR-enabled MERN application should now be running. When you access
http://localhost:3000, you'll see the server-rendered content.
Fetching Data:
You can fetch data on the server side in your React components using functions like
getServerSideProps (Next.js) or similar methods provided by other SSR frameworks. This is
useful for fetching data from your MongoDB database and rendering it on the server.
SEO Optimization:
With SSR, your content is available in the initial HTML response, which improves SEO. You
can further optimize SEO by setting appropriate meta tags and handling server-side redirects
for SEO-friendly URLs.
Deployment:
Deploy your SSR MERN application to a hosting provider or platform of your choice. Ensure
that your server is properly configured for production.
Basis of
Angular React
Distinction
Full-featured Framework – provides a The library is only concerned with UI
strong opinion on how your application components. MVC design requires
Purpose should be designed, as well as a number Flux to implement, but it provides
of tiny libraries that aid in the you more flexibility in how you wish
development of complex applications. to organise your code.
Supports both one way and two way
data binding ,two-way data binding One-way data binding means that a
Data
means that if we modify the UI input, UI element can’t affect a
binding
the model state will change, and vice component’s state.
versa.
TypeScript can write JavaScript XML
TypeScript is a statically typed language
Language (JSX), although it isn’t included by
that is a superset of JavaScript.
default.
Material Design Components – Angular Material-UI Library & Dependencies
UI includes a number of material design – Community-developed UI tools
Components components that make UI configuration provide a wide range of UI
a breeze. components.
Dependency injection is supported, React does not fully enable
Dependency
allowing for separate life cycles for dependency injection because each
Injection
different stores. component has its own global state.
Incremental DOM – when a new DOM Virtual DOM – anytime the DOM
is created, it compares it to the previous changes, a new virtual DOM is
DOM one and applies the differences to the created, compared to the previous one,
“actual” DOM, only allocating memory and only the differences are modified
if necessary. in the “real” DOM.
Key Difference of Angular vs React
• Purpose
• Data Binding
• Language
• UI Components
• Dependency Injection
• DOM
Advantages of Angular
Disadvantages of Angular
Advantages of React
Disadvantages of React
PROPS STATE
The Data is passed from one
The Data is passed within the component only.
component to another.
It is Immutable (cannot be
It is Mutable ( can be modified).
modified).
Props can be used with state and The state can be used only with the state
functional components. components/class component (Before 16.0).
Props are read-only. The state is both read and write.
Have you ever wondered how can we pass the data between the components
in ReactJS? We can pass the data between the components using Props and State. So,
let us know how we can pass the data using props and state and understand the
difference between the two.
We will learn about props and states with the help of an example project in ReactJS.
Props: Props are known as properties it can be used to pass data from one component
to another. Props cannot be modified, read-only, and Immutable.
Example: Modify the default code with the below code.
• Javascript
// App.js
import Fruit from './Fruit'
function App() {
const fruits =
{
name: "Mango",
color: "Yellow"
}
return (
<div className="App">
<Fruit fruits={fruits} />
</div>
);
}
return (
<div className="fruit">
<h1>List of Fruits</h1>
<p>Name: {props.fruits.name}</p>
<p>Color: {props.fruits.color}</p>
</div>
)
}
changeMessage() {
this.setState({
car: 'Jaguar'
})
}
render() {
return (
<div className="App">
<h1>{this.state.car}</h1>
<button onClick={() => this.changeMessage()}>
Change
</button>
</div>
)
}
}
• Javascript
// App.js
import './App.css';
import Fruit from './Fruit'
import Car from './Car';
function App() {
const fruits =
{
name: "Mango",
color: "Yellow"
}
return (
<div className="App">
<Fruit fruits={fruits} />
<hr></hr>
<Car />
</div>
);
}
7.
Flux: Flux is the application architecture or we can say JavaScript architecture that
uses for building client-side web applications or UI for client applications. you can
start using flux without a lot of new code. flux overcome the drawbacks of MVC such
as instability and complexity.
Example: In this example, we create a TODO list application. This example contains
functionality that you can add a task in the TODO list along with you can remove the
list of tasks.
Step 1: Create a new react app using the below commands.
devendra@root:~/Desktop$ npx create-react-app todoapp
devendra@root:~/Desktop/todoapp$ npm install redux react-redux –save
Step 2: Create a folder structure in your code editor as given below in the screenshot
you can create files manually or using commands as well.
Project Structure:
Step 3 (Actions): Actions are things that happen during the lifetime of your
application. In our application when the user clicks on create button a
function CRAETE_TODO will call and a new task will be added to the list. The
same DELETE_TODO function will perform a delete action when the Delete button
is clicked. This is an example of the Action component.
TodoActions.js
• Javascript
import dispatcher from "../dispatcher";
this.todos = [
{
id: 16561,
text: 'hello'
},
{
id: 16562,
text: 'another todo'
},
];
}
createTodo(text) {
const id = Date.now();
this.todos.push({
id,
text
});
this.emit('change');
}
deleteTodo(id) {
this.todos = this.todos.filter((elm) => {
return (elm.id != id);
});
this.emit('change');
}
getAll() {
return this.todos;
}
handleActions(action) {
switch (action.type) {
case 'CREATE_TODO': {
this.createTodo(action.text);
break;
}
case 'DELETE_TODO': {
this.deleteTodo(action.id);
break;
}
}
}
}
this.state = {
todos: TodoStore.getAll(),
};
this.inputContent = '';
}
render() {
return (
<div>
<h1> GFG Todo list</h1>
<input type="text" onChange=
{(evt) => this.inputContent = evt.target.value} />
<button onClick={() => TodoActions
.createTodo(this.inputContent)}>Create!</button>
<ul>{TodoComp}</ul>
</div>
);
}
}
Step 7: Now we will delete the task component.
Todo.js
• Javascript
import React from "react";
import * as TodoActions from '../actions/TodoActions';
render() {
return (
<li>
<span>{this.props.text}</span>
<button onClick={() => TodoActions
.deleteTodo(this.props.id)}>delete</button>
</li>
);
}
}
Step 8: Other components
index.js
• Javascript
import React from 'react';
import { render } from 'react-dom';
import Todolist from './pages/Todolist';
// render(React.createElement(Layout), app);
render(<Todolist />, app);
Step to run application: Open the terminal and type the following command.
npm start
Output:Create button will add a task to Todo list, similarly Delete button removes the
task from the Todo list
Redux: Redux is a predictable state container for JavaScript apps. Dan Abramov &
Andrew Clark developed Redux in 2015. Redux itself library that can be used with
any UI layer or framework, including React, Angular, Ember, and vanilla JS. Redux
can be used with React. both are independent of each other. Redux is a state managing
library used in JavaScript apps. It simply manages the state of your application or in
other words, it is used to manage the data of the application. It is used with a library
like React.
Example: Now we will see a simple example counter using react-redux. In this
example we store a state of button clicks and used that states for further buttons to
click for example we create four buttons increment (+), decrement (-), increment if
odd, increment async.
• increment (+), decrement (-): these two buttons will increment click by +1
and -1
• increment if odd: this button will only increment click if previous two
buttons (+)and (-) click is odd i.e. if the click is 7 then only this button will
increment by +1 and now clicks will be 8 otherwise this will not increment
if previous buttons (+) and (-) clicks were 6 because 6 is even
and increment if odd button only clicks when the previous state is odd
click.
• increment async: This button will increment click after halt or wait of 1000
mili. sec.
Below is the step by step implementation:
Step 1: Create a new react app using the below commands.
npx create-react-app counterproject
npm install redux react-redux --save
Step 2: Create all required Files and Folders.
Project Structure: It will look like the following.
incrementIfOdd() {
if (this.props.value % 2 !== 0) {
this.props.onIncrement()
}
}
incrementAsync() {
setTimeout(this.props.onIncrement, 1000)
}
render() {
const { value, onIncrement, onDecrement } = this.props
return (
<p>
<h1>GeeksForGeeks Counter Example</h1>
Clicked: {value} times
{' '}
<button onClick={onIncrement}>
+
</button>
{' '}
<button onClick={onDecrement}>
-
</button>
{' '}
<button onClick={this.incrementIfOdd}>
Increment if odd
</button>
{' '}
<button onClick={this.incrementAsync}>
Increment async
</button>
</p>
)
}
}
Counter.propTypes = {
value: PropTypes.number.isRequired,
onIncrement: PropTypes.func.isRequired,
onDecrement: PropTypes.func.isRequired
}
function setup(value = 0) {
const actions = {
onIncrement: jest.fn(),
onDecrement: jest.fn()
}
const component = shallow(
<Counter value={value} {...actions} />
)
return {
component: component,
actions: actions,
buttons: component.find('button'),
p: component.find('p')
}
}
it('third button should not call onIncrement if the counter is even', () => {
const { buttons, actions } = setup(42)
buttons.at(2).simulate('click')
expect(actions.onIncrement).not.toBeCalled()
})
describe('reducers', () => {
describe('counter', () => {
it('should provide the initial state', () => {
expect(counter(undefined, {})).toBe(0)
})
render()
store.subscribe(render)
Step to run the application: Open the terminal and type the following command.
npm start
Output:
Explain the use of CSS modules in React.
A very good point is that it is not necessary to configure WebPack: React handles everything
for you when you install create-React-app; thus, you don’t currently need to configure
Webpack for CSS Modules.
If you add Typescript to an existing React project, you will typically encounter an error while
utilizing CSS Modules. To resolve this, install Typescript with React using the following
command line.
There is no additional code needed or third-party code that you are adding to CSS Modules
while using them. You only need to change the CSS file name to “[filename].Modules.css”;
you can substitute any other name for “[filename]“. You must use the import keyword when
using CSS Modules to import the file to a specific component. You must specify the classes
when integrating CSS Modules into your React projects, like how you would access an
object’s property in standard Javascript using the dot notation or the bracket syntax.
<div className={classes.parent_div}></div>
You should use bracket notation if your CSS classes contain hyphens
<div className={classes.["parent-div"]}></div>
You can combine styles:
• By using CSS Modules, namespace conflicts for CSS classes are avoided. Multiple CSS
files may contain the same CSS class. Except for global styles, everything appears to
be quite stylish.
• In CSS Modules, you can send classes to multiple components.
• One of the key benefits of using CSS Modules is that you may edit any CSS file with
assurance and without concern for how it would affect other sites.
• Create portable and reusable CSS files with CSS Modules. There is no longer a need to
worry about rules affecting the styles of other components or selector name clashes.
• Despite the project’s complexity, CSS Modules make your code look tidy so that other
developers can read and comprehend it.
There are also some cons:
• Styles must be included as an object with a dot or bracket notation when integrating into
a project.
• In contrast to Styled Components, CSS Modules don’t accept props.
• In a time of working with global scope, CSS Modules will be a wrong choice.
So, why should we use CSS Modules?
• When using CSS Modules, you can be sure that every style for a given component is
present in one location and only applies to the component where it was imported.
• Ever ponder whether you could get rid of some fashion trends without causing damage
to something? Interested in knowing if the styles depended on other factors or stood
on their own? Or have you changed styles somewhere else? With the help of CSS
Modules and the concept of the local scope by default, the problem of global scope is
avoided.
• You’re constantly forced to think about the consequences as you write styles, resulting
in clear code.
• The issue of global scoping is avoided by using CSS Modules and the idea of the local
scope by default. As you choose your writing styles, you must consider the
implications.
• The style will not be applied, for example, if you use random-gross-class in HTML
without applying it as a CSS Modules-style class since the CSS selector will be
changed style random-gross value.
Functional components run from top to The class component is instantiated and
bottom and once the function is returned it different life cycle method is kept alive
can’t be kept alive. and is run and invoked depending on the
phase of the class component.
React lifecycle methods (for example, React lifecycle methods can be used
componentDidMount) cannot be used in inside class components (for example,
functional components. componentDidMount).
React uses Virtual DOM exists which is like a lightweight copy of the actual DOM(a
virtual representation of the DOM). So for every object that exists in the original
DOM, there is an object for that in React Virtual DOM. It is exactly the same, but it
does not have the power to directly change the layout of the document.
Manipulating DOM is slow, but manipulating Virtual DOM is fast as nothing gets
drawn on the screen. So each time there is a change in the state of our application, the
virtual DOM gets updated first instead of the real DOM.
When anything new is added to the application, a virtual DOM is created and it is
represented as a tree. Each element in the application is a node in this tree. So,
whenever there is a change in the state of any element, a new Virtual DOM tree is
created. This new Virtual DOM tree is then compared with the previous Virtual DOM
tree and make a note of the changes. After this, it finds the best possible ways to make
these changes to the real DOM. Now only the updated elements will get rendered on
the page again.
Ring of the UI is the most expensive part and React manages to do this most
efficiently by ensuring that the Real DOM receives batch updates to re-render the UI.
This entire process of transforming changes to the real DOM is called Reconciliation.
This significantly improves the performance and is the main reason why React and its
Virtual DOM are much loved by developers all around.
The diagrammatic image below briefly describes how the virtual DOM works in the
real browser environment .