Fs 5

Download as pdf or txt
Download as pdf or txt
You are on page 1of 47

UNIT V

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?

1. Cost-effective:All the four technologies that are mentioned


above, MERN (MongoDB, Express.js, React.js, and Node.js)
are used in MERN Stack is built on JavaScript that makes it
cost-effective and within less cost investment user will able to
get the better results or output.
2. SEO friendly:Here, SEO (Search Engine Optimization)
friendly means that Google, Yahoo and other search engines can
search each page on the website efficiently and easily, interpret
and correlate the content effectively with the searched text and
easily index it in their database. As whenever websites are
created using MERN technologies, then it is always SEO
friendly.
3. Better performance:Better performance refers to the faster
response between backend and front-end and database, which
ultimately improves the website speed and yields better
performance, thus providing a smooth user experience.
4. Improves Security: It mainly concerns the security of
applications generated using MERN; her web application
security refers to various processes, methods or technologies
used for protecting web servers and various web applications,
such as APIs (Application user interface) from the attack by
internet-based threats. Generally, secured hosting providers can
easily integrate applications created using the MERN stack. For
more or better security Mongo DB and Node.js security tools
are also used.
5. Provide the fastest delivery:Any Web applications and mobile
applications created by using MERN Stack are built much
faster, which also helps to provide faster delivery to our clients.
6. Provides faster Modifications: MERN stack technologies
supports quick modifications as per the client's request in the
mobile and web applications.
7. Open Source: All the four technologies that are involved in
MERN are open-source. This feature allows developers to get
solutions to queries that may evolve from the open portals
during development. As a result, it will be ultimately beneficial
for a developer.
8. Easy to switch between client and server: MERN is very
simple and fast because it is written in only one language. And
also, it is very easy to switch between client and server.
Architectural Structure of MERN Stack and its
working?
MERN has a 3-tier Architecture system mainly consisting of 3 layers
-
These layers are as follows:
1. Web as front-end tier
2. Server as the middle tier
3. Database as backend tier
We already know that it comprises 4 components, i.e., MongoDB,
Express.js, React, Node.js.
Now let us understand in more detail about these three tiers which are
mentioned above -
i. Web or front-end tier - The top tier of the MERN stack is
mainly handled by React.js. It is one of the most prominent used
open-source front-end JavaScript libraries used for building
Web applications. It is famous for creating dynamic client-side
applications. React will help you construct complex interfaces
by using single components. It also connects those complex
interfaces to data available on the backend server. React is used
to create mobile applications (React Native) and web
applications. React allows the reusability of code and can easily
support it, which has many benefits and is much time saver. It
permits users to create large web applications that can easily
change the data of the page even without reloading the page.
ii. Server or middle-tier - It is just next level from the top layer
and is mainly handled by two components of the MERN stack,
i.e., Express.js and Node.js. These two's components handle it
simultaneously because Express.js maintained the Server-side
framework, running inside the Node.js server. Express.js is one
of the widely used backend development JavaScript
Frameworks. It allows developers to spin up robust APIs
(Application Programming Interface) and web servers much
easier and simpler. It also adds helpful functionalities to Node.js
HTTP (HyperText Transfer Protocol) objects. Whereas on the
other hand, Node.js plays a very important role in itself. It is an
open-source server environment, and it is a cross-platform
runtime environment for executing JavaScript code outside a
browser. Node.js continuously uses JavaScript; thus, it's
ultimately helpful for a computer user to quickly create any net
service or any net or mobile application.
iii. Database as backend tier - It is one of the most important
levels of the MERN Stack and is mainly handled by MongoDB;
the main role of a database is to store all the data related to your
application, for example - content, statistics, information, user
profiles, comments and so on. It mainly stores all the data
for safety purposes. It maintains a proper record, which usually
returns the data to the user whenever required. It mainly stores
the data in the database. It generates two or more replica files of
the data so that whenever the system fails, it can retrieve the
exact information or data that the user wanted earlier. It implies
that MongoDB is not based on the table-like relational database
structure. On the other hand, it provides an altogether different
mechanism for the retrieval and storage of data. Mongo DB is
the most popular NoSQL (NoSQL or Non Structured Query
Language) database, an open-source document-oriented
database. The term 'NoSQL' typically means a non-relational
database that does not require a fixed schema or proper
relational tables to store the necessary data in it. MongoDB
stores the data in a different format other than the relational
tables, consisting of rows and columns.
Major Components of MERN Stack
Let us understand one by one about the four technologies or
components that play a major role in forming MERN Stack:
I. MongoDB -
o Mongo DB is the most popular NoSQL (NoSQL or Non
Structured Query Language) database, an open-source
document-oriented database.
o The term 'NoSQL' typically means a non-relational database that
does not require a fixed schema or proper relational tables to
store the necessary data in it. MongoDB stores the data in a
different format other than the relational tables, consisting of
rows and columns.
o It implies that MongoDB is not based on the table-like relational
database structure. On the other hand, it provides an altogether
different mechanism for the retrieval and storage of data.
o The storage format in which the data is stored is known as
BSON, which stands for Binary JavaScript Object Notation; its
binary structure encodes length and type of information, which
allows it to be parsed much more quickly.
o MongoDB uses BSON when storing documents in collections.
o It allows a highly scalable and flexible document structure.
o It is very faster as compared to RDBMS due to its efficient
storage and indexing techniques.
o In MongoDB, complex join operations are not available; hence, it
cannot support complex transactions.
o MongoDB uses JavaScript for coding as a language which is one
of the great advantages.
o It is Schemaless as any data stored which is stored in a separate
document.
o In MongoDB, there is no concept of relationships or table
formations, as this is happening in RDBMS (Relational
Database Management System), in which tables have a certain
relation between them.
o It also supports a flexible document model, which is very fast for
any developer to create.
o MongoDB is one of the important types of NoSQL Databases. It
is more scalable and provides excellent performance if we
notice that it will reach its scaling limit whenever a database
runs on a single server.
o MongoDB is a NoSQL database that scales by adding more and
more servers and increases productivity with its flexible
document model.
Some important features of MongoDB -
o Schema-less Database: MongoDB has this one of the great
features, which means that one collection can hold different
types of documents in it. Due to this extraordinary feature,
MongoDB provides great flexibility to databases. In the
MongoDB database, a single collection comprises multiple
documents, and these documents may further comprise the
different numbers of values, fields, and so on. One document
doesn't need to be a must to relate with the other documents, as
it happens in relational databases.
o Indexing: In the MongoDB database, one can easily fetch out the
necessary data from the data pool due to this indexing feature. In
MongoDB, every data item has provided a particular index,
categorized as primary and secondary indices. With this
indexing, data retrieval is easier for the user; it saves a lot of
time. If the data is not indexed, the database searches each
document with the specified query, which takes lots of time and
is inefficient.
o Document Oriented: In MongoDB, all the data has been stored
in documents instead of tables like SQL. Also, these documents
have their unique object id. In these documents, the informative
data is stored in fields, i.e., key-value pairs instead of columns
and rows, making the data much more flexible and easier to
fetch out rather than applying queries for every data compared
to RDBMS.
o Faster - MongoDB is very fast compared with relational
database (RDBMS), which is document-oriented. Each data
item has its index value, making it easier for us to retrieve any
data without wasting time writing queries and making logic
accordingly.
o Scalability: MongoDB is more scalable with the help of
sharding. It provides horizontal scalability. Here the term
sharding means distributing data on multiple servers; in this, a
large amount of data has been divided into multiple small data
chunks with the help of shard key. These types of data
chunks are evenly distributed across shards that reside across
many physical servers.
o High Performance: MongoDB has very high performance and
has data persistency as compared to other databases due to the
presence of its great features like indexing, scalability,
replication, etc.
o Replication and Highly Available - MongoDB increases the
availability of data due to creating multiple copies of data on
different servers. Providing redundancy or data replication
ultimately protects the database from any hardware failure and
protects the data from being lost in the future. I suppose if one
server was not working or clashes due to error, and then data can
easily be retrieved from other active servers, who are currently
working at that time, this will all be due to redundancy of data.
o Aggregation: This feature of MongoDB is quite similar to the
SQL GROUPBY clause. This GROUPBY clause performs
various operations on the grouped data to get the unique or
computed
o Simple Environment Setup - MongoDB has a very simple
environment setup. One can easily set up MongoDB in their
system without applying much effort.
II. Express

o Express is a JavaScript server-side framework that runs within js.


o It is one of the best backend development JavaScript
Frameworks.
o It provides the developer with a platform to create and maintain
robust servers.
o Express is used for building and designing web and mobile
applications easily and quickly.
o Express is used to provide server-side logic for mobile and web
applications, and as such, it is used all over the place.
o It allows developers to spin up robust APIs (Application
Programming Interface) and web servers much easier and
simpler.
o Express makes robust web servers easier to organize your
application's functionality with routing and middleware.
o It also adds helpful functionalities to Node.js HTTP (HyperText
Transfer Protocol) objects.
o It is an important component of the MERN and MEAN Stack and
is used to build fast, maintainable, and robust productions web
applications.
Some important features of Express -

o Express makes Node.js web and mobile application development


much easier and faster.
o Express has a very simple environment setup. One can easily set
up Express in their system and configure it without applying
much effort.
o Express is very easy to connect with Databases like MongoDB.
o Based on HTTP methods and URLs, Express allows you to
define the routes of your application.
o Routing mainly aims to describe code that needs to be run in
response to any request received by a server. Routing is
generally done based on the sequence of URL patterns and the
HTTP method, which is associated with the request.
o If you want to perform additional tasks and functions on any
request and response, you can easily use various middleware
modules present in Express.
o The request is a message that arrives at the server for requesting
something, and a Response is a message sent by the server to a
client in the form of the result of whatever the client asked for.
o If any error occurs and you want to handle it, you can easily
handle it by using error handling middleware.
o Middleware is used somewhere during the lifecycle of request or
response in the form of code. It is mainly used to add
functionalities or augment the behaviour of the webserver.
o Express also facilitates you to create a REST
API (Representational State Transfer Application Programming
Interface)
o The REST APIs is also known as RESTful API, It mainly
conforms to the constraints of REST architectural style, and it
also allows for interaction with RESTful web services. The
main advantage of REST API is that it provides great flexibility;
it uses HTTP requests to access and use data.
o The data flow into a website structure can easily facilitate by
using the two template engines, EJS and Jade, provided by
Express.
o Express has a gigantic suite of third-party add-ons so that
developers can use it to provide better functionality, helps to
increase the security level, and improve speed.
o It is very efficient and scalable; one can easily access it from
anywhere and use it simultaneously on different systems, and
very fast.
o It is Single-threaded and Asynchronous.
o It also has the biggest community for Node.js.
o With its built-in router, it promotes code reusability.
o If we want to understand the architecture behind web servers and
their working along with the organization, then learning Express
is the best option.
III. React

o React is one of the most popular open-source front-end


JavaScript libraries used for building Web applications.
o Before using react, it has some prerequisites that one should
follow, that you must download Node packages in your system
with their latest versions. Also, you must have an understanding
of HTML, CSS and JavaScript.
o It is used to build user interfaces, especially for a single page web
application.
o It is not a JavaScript framework. It is just a JavaScript library
developed by Facebook to solve problems we could not solve
earlier using other libraries while building web and mobile
applications.
o React is also used for making a grip over the view layer for
mobile and web applications.
o It allows us to create reusable UI ( User Interface ) components.
o It was first created by software engineer Jordan Walke, who
works for Facebook.
o React was first deployed in the Facebook news feed.
o It allows developers to create large web applications that can
easily change the data of the page even without reloading the
page.
o The main objective of reacting is that it only works on user
interfaces in the application, whether mobile or web.
o It is very fast, simple and scalable.
o React is also used with a combination of other JavaScript
libraries or frameworks.
o There are a lot of open-source platforms that are also used to
make the front-end web and mobile applications easier, like
Angular js in MVC, but still, React replaces the Angular from
the MEAN stack. Now, most developers are using the MERN
stack in which react is used; the main reason is that it is very fast
and has more advantages over other front-end frameworks.
Some important features of React -

o Easy to learn - One of the great advantages of using react as it is


very easier for a beginner to learn it and make web and mobile
applications using this front-end framework. Anyone with a
piece of previous basic knowledge in programming can easily
understand React compared to Angular. Angular is referred to as
a ' Domain Specific Language ', so it is implied that it is quite
difficult to understand it. For Learning React, you need the basic
knowledge of CSS and HTML.
o Simple - React is one of the simplest open-source JavaScript
front-end frameworks for building web and mobile applications.
It uses the component-based approach, uses plain and simple
JavaScript, and a well-defined lifecycle, which makes react
much simpler and easier. So that one can easily learn it and
build professional mobile and web applications. It uses a simple
syntax named JSX, which allows learners or developers to mix
HTML with JavaScript to make it easier for them to apply and
use it for making efficient web and mobile applications.
However, it is not required to use JSX, you can either use plain
JavaScript, but as compared to JSX, JSX is the much better
option over it due to its simplicity and easier syntax.
o Data Binding - React uses an application architecture known as
Flux to control data flow to components via one control point
called the dispatcher. It uses one-way data binding, which is
easier to debug self-contained components of large React
applications.
o Native Approach - React is used to create mobile applications
(React Native) and web applications. React allows the
reusability of code and can easily support it, which has many
benefits and is much time saver. So simultaneously, at the same
time, we can make IOS, Web applications and Android.
o Performance - React has very fast performance due to the
immutability of data. As the name suggests, we can predict that
the immutable data structures never change and allows you to
compare direct object references instead of doing deep-tree
comparisons. The above reason ultimately affects the
performance of reacting and makes it faster.
o Testability - React is very easy to test; whatever applications we
are generating from the react, whether mobile or web
applications, it is much easier for us to test it on react. There are
some state functions in the react, where various react views are
treated as these functions of the states, and we can easily
manipulate with the state we pass to the react view. Also, we can
take a look at the output and triggered actions, functions, events,
etc.
IV. Node.js

o js is an open-source server environment, and it is a cross-


platform runtime environment for executing JavaScript code
outside a browser.
o js is not a programming language, and even it is not a framework.
o It is often used for building and developing numerous backend
services like net applications, mobile applications.
o Massive corporations principally utilize it in production
like Uber, PayPal, Netflix,
o It may be a free ASCII text file platform and may be utilized by
anybody.
o It will run on numerous operative systems like Windows, Mac,
Linux, Unix, etc.
o It is incredibly simple to urge started with it and may even be
used for agile development and prototyping.
o It provides extremely ascendable and really quick services to the
users.
o It is incredibly consistent and may be used as an ASCII text file
cleaner.
o It continuously uses JavaScript; thus, it's ultimately helpful for a
computer user to quickly create any net service or any net or
mobile application.
o It provides a massive system for any ASCII text file library.

o It contains a Non-blocking or, can say, Asynchronous nature.

Some important features of React -


o Easy Scalability: js is highly scalable because it uses a single-
threaded model with event looping. The server usually responds
in a non-blocking way due to the help of the event mechanism.
It also makes the server very scalable instead of traditional
servers that create limited threads to handle requests. Node.js
uses a single-threaded program, and this program will be able to
provide service to many requests.
o Fast: The event loop in Node.js handles all asynchronous
operations, so Node.js acts like a fast suite, and all the
operations in Node.js are performed quickly like network
connection, reading or writing in the database, or file system. It
runs on the V8 engine developed by Google.
o Easy to learn and debug code: js is quite easy to learn and
debug because it uses JavaScript for running code of web-based
projects and various web and mobile applications. If you have
excelled in front-end developing and have a good command of
JavaScript, you can easily build and run the application on
Node.js and explore more as much you can; it depends on your
capability.
o Real-time web apps: js plays a key role in making real-time web
applications. And If you are building a mobile or a web
application, you can also use PHP, although it will take the same
time duration as when you use Node.js. Still, if someone wants
to build gaming apps and chat applications, then Node.js is a
much better option because of its faster synchronization.
o Caching Advantage: js provides the caching property in which a
single module is cached. Sometimes you do not need to re-
execute the same lines of code because it has already been
cached using Node.js.
o Data Streaming:In Node.js, hypertext transfer protocol ( HTTP )
requests and responses area unit thought-about as 2 separate
events. They're knowledge streams, thus once you method a file
at the time of loading, it'll scale back the time and create it
quicker once the info is given within the style of transmissions.
It additionally permits you to stream audio and video files at
lightning speed.
o Object-Oriented Approach: A huge complaint against Node.js
was its JavaScript heritage, which frequently involved many
procedural spaghetti codes. Frameworks like Coffee Script and
Typescript solved these issues but came as a bolt-on for those
who seriously cared about coding standards. With the release
and general adoption of ES6, Classes are built into the
framework, and the code looks syntactically similar to C#, Java
and SWIFT.
o Event-Driven and Asyncronization- All Apis of the Node.js
library area unit asynchronous, that is, non-blocking. It suggests
that a Node.js based mostly server ne'er waits for associate API
to come back knowledge. The server moves to the consequent
API once line it, and a notification mechanism of Events of
Node.js helps the server to urge a response from the previous
API decision.
o Corporate Support: There are a lot of famous companies like
PayPal, Wal-Mart, Microsoft, Google that are using Node.js for
building the applications. Node.js uses JavaScript, so most
companies are combining front-end and backend Teams into a
single unit.
Advantages of MERN Stack
There are a lot of advantages of MERN Stack, some of them are
mentioned below -
1. For a smooth development of any web application or mobile
app, it supports MVC (Model View Controller) architecture;
the main purpose of this architecture is to separate the
presentation details with the business logic.
2. It covers all the web development stages starting from front-end
development to backend development with JavaScript.
3. It is an open-source framework mainly used to develop web-
based or mobile applications and is supported by the
community.
4. It is very fast and efficient compared to MEAN Stack and
mostly suitable for small applications, whereas MEAN Stack is
suitable for developing large applications.
Build a Basic React App that Display “Hello
World!”
React is a Javascript Library that was created by Facebook for building better
User Interface(UI) web applications and mobile applications. It is an open
source library for creating interactive and dynamic applications.
In this article, we will see how to build a basic react app that shows hello world.
• Tocreate a react application, Node.js version of at least 10 or higher
need to be installed on your system. If it is installed you can check by
using the following command in your command line.
node -v

• Make sure you have a code editor for working on your project files.

Let’s create our first react application:

To build a react application follow the below steps:


Step 1: Create a react application using the following command

npx create-react-app foldername

It takes a couple of minutes to install the packages.

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 (

<h1> Hello World! </h1>

);
}
export default App;
Step to run the application: Enter the following command to run the
application.
npm start

Output: You will see the following output in your browser.

Congratulations, you have created your first React app.

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.

Rendering Components in ReactJS


React is also capable of rendering user-defined components. To render a
component in React we can initialize an element with a user-defined component
and pass this element as the first parameter to ReactDOM.render() or directly
pass the component as the first argument to the ReactDOM.render() method.

The below syntax shows how to initialize a component to an element:


const elementName = <ComponentName />;
In the above syntax, the ComponentName is the name of the user-defined
component.
Note: The name of a component should always start with a capital letter. This is
done to differentiate a component tag from HTML tags.
The below example renders a component named Welcome to the Screen:
Open your index.js file from your project directory, and make the given below
changes:
src index.js:
javascript
import React from 'react';
import ReactDOM from 'react-dom';

// This is a functional component


const Welcome = () => {
return <h1>Hello World!</h1>
}

ReactDOM.render(
<Welcome />,
document.getElementById("root")
);
Output:

Let us see step-wise what is happening in the above example:


• We call the ReactDOM.render() as the first parameter.
• React then calls the component Welcome, which returns <h1>Hello
World!</h1>; as the result.
• Then the ReactDOM efficiently updates the DOM to match with the
returned element and renders that element to the DOM element with id
as “root”.
React State
The state is an updatable structure that is used to contain data or information
about the component. The state in a component can change over time. The
change in state over time can happen as a response to user action or system
event. A component with the state is known as stateful components. It is the
heart of the react component which determines the behavior of the component
and how it will render. They are also responsible for making a component
dynamic and interactive.
A state must be kept as simple as possible. It can be set by using
the setState() method and calling setState() method triggers UI updates. A state
represents the component's local state or information. It can only be accessed or
modified inside the component or by the component directly. To set an initial
state before any interaction occurs, we need to use the getInitialState() method.
For example, if we have five components that need data or information from
the state, then we need to create one container component that will keep the
state for all of them.
Defining State
To define a state, you have to first declare a default set of values for defining the
component's initial state. To do this, add a class constructor which assigns an
initial state using this.state. The 'this.state' property can be rendered
inside render() method.
Example
The below sample code shows how we can create a stateful component using
ES6 syntax.
1. import React, { Component } from 'react';
2. class App extends React.Component {
3. constructor() {
4. super();
5. this.state = { displayBio: true };
6. }
7. render() {
8. const bio = this.state.displayBio ? (
9. <div>
10. <p>
<h3>Javatpoint is one of the best Java training institute in Noida, Delhi,
Gurugram, Ghaziabad and Faridabad. We have a team of experienced Jav
a developers and trainers from multinational companies to teach our cam
pus students.</h3></p>
11. </div>
12. ) : null;
13. return (
14. <div>
15. <h1> Welcome to JavaTpoint!! </h1>
16. { bio }
17. </div>
18. );
19. }
20. }
21. export default App;
To set the state, it is required to call the super() method in the constructor. It is
because this.state is uninitialized before the super() method has been called.
Output

Changing the State


We can change the component state by using the setState() method and passing
a new state object as the argument. Now, create a new method
toggleDisplayBio() in the above example and bind this keyword to the
toggleDisplayBio() method otherwise we can't access this inside
toggleDisplayBio() method.
1. this.toggleDisplayBio = this.toggleDisplayBio.bind(this);
Example
In this example, we are going to add a button to the render() method. Clicking
on this button triggers the toggleDisplayBio() method which displays the
desired output.
1. import React, { Component } from 'react';
2. class App extends React.Component {
3. constructor() {
4. super();
5. this.state = { displayBio: false };
6. console.log('Component this', this);
7. this.toggleDisplayBio = this.toggleDisplayBio.bind(this);
8. }
9. toggleDisplayBio(){
10. this.setState({displayBio: !this.state.displayBio});
11. }
12. render() {
13. return (
14. <div>
15. <h1>Welcome to JavaTpoint!!</h1>
16. {
17. this.state.displayBio ? (
18. <div>
19. <p>
<h4>Javatpoint is one of the best Java training institute in Noida, Delhi,
Gurugram, Ghaziabad and Faridabad. We have a team of experienced Jav
a developers and trainers from multinational companies to teach our cam
pus students.</h4></p>
20. <button onClick=
{this.toggleDisplayBio}> Show Less </button>
21. </div>
22. ):(
23. <div>
24. <button onClick=
{this.toggleDisplayBio}> Read More </button>
25. </div>
26. )
27. }
28. </div>
29. )
30. }
31. }
32. export default App;
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.

Express Rest API


An API is always needed to create mobile applications, single page applications, use AJAX
calls and provide data to clients. An popular architectural style of how to structure and name
these APIs and the endpoints is called REST(Representational Transfer State). HTTP
1.1 was designed keeping REST principles in mind. REST was introduced by Roy
Fielding in 2000 in his Paper Fielding Dissertations.
RESTful URIs and methods provide us with almost all information we need to process a
request. The table given below summarizes how the various verbs should be used and how
URIs should be named. We will be creating a movies API towards the end; let us now discuss
how it will be structured.
Method URI Details Function
GET /movies Safe, Gets the list of all movies and their details
cachable
GET /movies/1234 Safe, Gets the details of Movie id 1234
cachable
POST /movies N/A Creates a new movie with the details provided.
Response contains the URI for this newly created
resource.
PUT /movies/1234 Idempotent Modifies movie id 1234(creates one if it doesn't
already exist). Response contains the URI for this
newly created resource.
DELETE /movies/1234 Idempotent Movie id 1234 should be deleted, if it exists.
Response should contain the status of the request.
DELETE /movies Invalid Should be invalid. DELETE and PUT should
or PUT specify which resource they are working on.

The express() function is a top-level function exported by the express module.


var express = require('express')
var app = express() // Creates an Express application.

Express is a fast, assertive, essential and moderate web framework of Node.js.


You can assume express as a layer built on the top of the Node.js that helps
manage a server and routes. It provides a robust set of features to develop web
and mobile applications.

Express Api Server Architecture

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();

var app = express();

app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(upload.array());

//Require the Router we defined in movies.js


var movies = require('./movies.js');
app.use('/movies', movies);

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}
];

//Routes will go here


module.exports = router;
GET routes
Let us define the GET route for getting all the movies −
router.get('/', function(req, res){
res.json(movies);
});
To test out if this is working fine, run your app, then open your terminal and
enter −
curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X
GET
localhost:3000/movies
The following response will be displayed −
[{"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}]
We have a route to get all the movies. Let us now create a route to get a specific
movie by its id.
router.get('/:id([0-9]{3,})', function(req, res){
var currMovie = movies.filter(function(movie){
if(movie.id == req.params.id){
return true;
}
});
if(currMovie.length == 1){
res.json(currMovie[0])
} else {
res.status(404);//Set status to 404 as movie was not found
res.json({message: "Not Found"});
}
});
This will get us the movies according to the id that we provided. To check the
output, use the following command in your terminal −
curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X
GET
localhost:3000/movies/101
You'll get the following response −
{"id":101,"name":"Fight Club","year":1999,"rating":8.1}
If you visit an invalid route, it will produce a cannot GET error while if you
visit a valid route with an id that doesn’t exist, it will produce a 404 error.
We are done with the GET routes, let us now move on to the POST route.
POST route
Use the following route to handle the Posted data −
router.post('/', function(req, res){
//Check if all fields are provided and are valid:
if(!req.body.name ||
!req.body.year.toString().match(/^[0-9]{4}$/g) ||
!req.body.rating.toString().match(/^[0-9]\.[0-9]$/g)){

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 AND WEBPACK

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.

Collaboration: Team members can work on different modules simultaneously without


interfering with each other’s code.

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.

Why Webpack in React?


Webpack offers several advantages when working with React:

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.

Dependency Management: It handles dependencies between modules, ensuring that each


module gets the necessary resources it requires.

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.

Using Webpack in React


To use Webpack in a React project:

Installation: Install Webpack and related packages using npm or yarn.


Configuration: Create a webpack.config.js file to specify entry points, output paths, loaders,
and plugins. This is where you define how Webpack should process your code.

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.

Plugins: Enhance Webpack’s functionality with plugins, such as HtmlWebpackPlugin for


generating HTML files or MiniCssExtractPlugin for extracting CSS into separate files.

Code Splitting in React

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.

Strategies for Code Splitting


Dynamic Imports: Use the dynamic import() function to load modules asynchronously when
required. This is excellent for lazy-loading components.

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.

Components in React Router


There are two types of router components:
o <BrowserRouter>: It is used for handling the dynamic URL.
o <HashRouter>: It is used for handling the static request.
Example
Step-1: In our project, we will create two more components along with App.js, which is
already present.
About.js

1. import React from 'react'


2. class About extends React.Component {
3. render() {
4. return <h1>About</h1>
5. }
6. }
7. export default About
Contact.js

1. import React from 'react'


2. class Contact extends React.Component {
3. render() {
4. return <h1>Contact</h1>
5. }
6. }
7. export default Contact
App.js

1. import React from 'react'


2. class App extends React.Component {
3. render() {
4. return (
5. <div>
6. <h1>Home</h1>
7. </div>
8. )
9. }
10. }
11. export default App
Step-2: For Routing, open the index.js file and import all the three component files in it.
Here, you need to import line: import { Route, Link, BrowserRouter as Router } from
'react-router-dom' which helps us to implement the Routing. Now, our index.js file looks
like below.
What is Route?
It is used to define and render component based on the specified path. It will accept
components and render to define what should be rendered.
Index.js

1. import React from 'react';


2. import ReactDOM from 'react-dom';
3. import { Route, Link, BrowserRouter as Router } from 'react-router-dom'
4. import './index.css';
5. import App from './App';
6. import About from './about'
7. import Contact from './contact'
8.
9. const routing = (
10. <Router>
11. <div>
12. <h1>React Router Example</h1>
13. <Route path="/" component={App} />
14. <Route path="/about" component={About} />
15. <Route path="/contact" component={Contact} />
16. </div>
17. </Router>
18. )
19. ReactDOM.render(routing, document.getElementById('root'));
Step-3: Open command prompt, go to your project location, and then type npm start. You
will get the following screen.

Now, if you enter manually in the browser: localhost:3000/about, you will


see About component is rendered on the screen.

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

1. import React from 'react';


2. import ReactDOM from 'react-dom';
3. import { Route, Link, BrowserRouter as Router } from 'react-router-dom'
4. import './index.css';
5. import App from './App';
6. import About from './about'
7. import Contact from './contact'
8.
9. const routing = (
10. <Router>
11. <div>
12. <h1>React Router Example</h1>
13. <Route exact path="/" component={App} />
14. <Route path="/about" component={About} />
15. <Route path="/contact" component={Contact} />
16. </div>
17. </Router>
18. )
19. ReactDOM.render(routing, document.getElementById('root'));
Output

SERVER SIDE RENDERING


Server-side rendering (SSR) in a MERN (MongoDB, Express.js, React, Node.js) stack
involves rendering React components on the server side and sending the fully rendered
HTML to the client, as opposed to the traditional client-side rendering (CSR) where the
browser downloads JavaScript and renders components on the client side. SSR can improve
SEO, initial page load performance, and user experience.

Here's a step-by-step guide on how to implement SSR in a MERN stack:

Set Up Your MERN Application:


Make sure you have a basic MERN application with MongoDB for data storage, Express.js
for the server, React for the frontend, and Node.js as the runtime.

Choose a SSR Framework:


There are several SSR frameworks available for React applications. Some popular ones
include Next.js, Razzle, and After.js. For this example, we'll use Next.js.

Install Next.js:
Install Next.js in your project:

npm install next react react-dom

Create a Next.js App:


Create a new directory for your Next.js app and set up the necessary folder structure:

- pages/
- index.js
The pages directory is where you create your routes. In this example, we have a single route
for the homepage.

Create a Basic React Component:

Create a React component in pages/index.js:

import React from 'react';


const Home = () => {
return (
<div>
<h1>Hello, SSR in MERN Stack!</h1>
</div>
);
};

export default Home;

Update Your Server:


Modify your Express.js server to handle SSR using Next.js. Create an Express server that
uses Next.js as middleware.

const express = require('express');


const next = require('next');

const dev = process.env.NODE_ENV !== 'production';


const app = next({ dev });
const handle = app.getRequestHandler();

app.prepare().then(() => {
const server = express();

// Handle all requests through Next.js


server.get('*', (req, res) => {
return handle(req, res);
});

server.listen(3000, () => {
console.log('Server is running on port 3000');
});
});

Start your server by running:


node server.js

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.

That's a basic overview of implementing server-side rendering in a MERN stack using


Next.js as an example. The specific details may vary depending on your project requirements
and choice of SSR framework, but this should give you a good starting point.

Explain about How is React different from Angular?

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

• Clean code development is available.


• Increased Efficiency
• Interface Inspired by Material Design
• Because an angular framework can handle routing, switching from one
view to another is simple.
• Angular CLI for Seamless Updates

Disadvantages of Angular

• For newbies, an angular feature can be perplexing.


• Thereisn’t a clear manual or comprehensive, all-encompassing
documentation.
• The learning curve is steep.
• Limited Routing makes it difficult to debug scopes.
• When pages have interactive components, Angular can become slow.
• Integration with third parties is extremely tough.
• Several
complications may arise when upgrading from earlier versions to
newer versions.

Advantages of React

• Because of its straightforward design, it is simple to learn.


• TheHTML-like syntax enables for templating as well as extensive
documentation.
• Developerscan spend less time worrying about framework-specific code
and more time writing current JavaScript.
• Improve server-side rendering capability, making it a more robust platform
for content-focused apps.
• React allows you to migrate between versions.
• Facebook has a feature called “codemod” that automates a lot of the
process.
• React skills can be transferred to Native development.
• ReactJS is ideal for managing huge loads with relative ease when
combined with ES6/7.

Disadvantages of React

• Integrating Reacts with a typical MVC framework like Rail necessitates a


lot of setup.
• Users using ReactJS would need a thorough understanding of how to
integrate a user interface with the MVC framework.
What are the differences between state and props?

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.

Steps to Create React Project:

Step 1: Create a React application using the following command:


npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the
following command:
cd foldername
Project Structure:
Project Structure

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>
);
}

export default App;


• CSS
/* App.css */
.App {
text-align: center;
}
Create a Component known as Fruit.js and add the below code:
• Javascript
import React from "react"

const Fruit = (props) => {

return (
<div className="fruit">
<h1>List of Fruits</h1>
<p>Name: {props.fruits.name}</p>
<p>Color: {props.fruits.color}</p>
</div>
)
}

export default Fruit;


Step to Run Application: Run the application using the following command from the
root directory of the project:
npm startOutput:
The following will be the output when we execute the above command. The data will
be passed from the Parent component i.e. App.js to the Child component i.e. Fruit.js
with the usage of the “Props” feature.
State: The state represents parts of an Application that can change. Each component
can have its State. The state is Mutable and It is local to the component only.
Example: Let us create a Class component named Car.js within the same
project “fruits”.
Add the following code in the Car.js component.
• Javascript
import React, { Component } from "react"

class Car extends Component {


constructor() {
super()
this.state = {
car: 'Ferrari'
}
}

changeMessage() {
this.setState({
car: 'Jaguar'
})
}

render() {
return (
<div className="App">
<h1>{this.state.car}</h1>
<button onClick={() => this.changeMessage()}>
Change
</button>
</div>

)
}
}

export default Car

• 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>
);
}

export default App;


Step to Run Application: Run the application using the following command from the
root directory of the project:
npm start
Output:
The following will be the output when we execute the above command. The data is
local to the component “Car” only and it can be updated using the button change in
the screen.

Explain about How is Redux different from Flux?

Sr.no Redux Flux


It was developed by Dan Abramov &
1. It was developed by Facebook.
Andrew Clark.
It is Application architecture
It is an Open-source JavaScript library used
2. designed to build client-side web
for creating the UI.
apps.
Flux has main four components :
Redux has mainly two components • Action
3. • Action Creator • Dispatcher
• Store • Store
• View
4. Redux does not have any dispatcher. Flux has a single dispatcher.
Redux has only a single store in the Flux has multiple stores in one
5.
application. application.
6. In Redux, Data logics are in the reducers. In flux, Data logic is in store.
In flux store’s state can be
In Redux store’s state cannot be mutable mutable.

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:

todo app folder 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";

/* Create task function */


export function createTodo(text) {
dispatcher.dispatch({
type: "CREATE_TODO",
text,
});
}

/* Delete task function */


export function deleteTodo(id) {
dispatcher.dispatch({
type: "DELETE_TODO",
id,
});
}
Step 4: Dispatchers
Think of the Dispatcher as a router. Actions are sent to the Dispatcher who calls the
appropriate callbacks.
dispatcher.js
• Javascript
import { Dispatcher } from "flux";

export default new Dispatcher;


Step 5 (Store):
A store is a place that holds the app’s state. It is very easy to create a store once you
have reducers. We are passing store property to the provider element, which wraps our
route component.
• Javascript
import { EventEmitter } from 'events';

import dispatcher from '../dispatcher';

class TodoStore extends EventEmitter {


constructor() {
super();

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;
}
}
}
}

const todoStore = new TodoStore();


dispatcher.register(todoStore.handleActions.bind(todoStore));
export default todoStore;
Step 6 (Root Component): The index.js component is the root component of the app.
Only the root component should be aware of a redux. The important part to notice is
the connect function which is used for connecting our root component App to the
store. This function takes a select function as an argument. The select function takes
the state from the store and returns the props (visibleTodos) that we can use in our
components.
Todolist.js
• Javascript
import React from 'react';
import Todo from '../components/Todo';
import TodoStore from '../stores/TodoStore.js';
import * as TodoActions from '../actions/TodoActions';

export default class Todolist extends React.Component {


constructor() {
super();

this.state = {
todos: TodoStore.getAll(),
};
this.inputContent = '';
}

// We start listening to the store changes


componentWillMount() {
TodoStore.on("change", () => {
this.setState({
todos: TodoStore.getAll(),
});
});
}

render() {

const TodoComp = this.state.todos.map(todo => {


return <Todo key={todo.id} {...todo} />;
});

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

export default class Todo extends React.Component {

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

const app = document.getElementById('root');

// 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.

files and folders

Step 3: Counter.js is a Presentational Component, which is concerned with how things


look such as markup, styles. It receives data and invokes callbacks exclusively via
props. It does not know where the data comes from or how to change it. It only
renders what is given to them. This is the root component for the counter to render
everything in UI.
Counter.js
• Javascript
import React, { Component } from 'react'
import PropTypes from 'prop-types'

class Counter extends Component {


constructor(props) {
super(props);
this.incrementAsync = this.incrementAsync.bind(this);
this.incrementIfOdd = this.incrementIfOdd.bind(this);
}

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
}

export default Counter


Step 4: Counter.spec.js contains what to change when particular buttons of
components are clicked.
• Javascript
import React from 'react'
import { shallow } from 'enzyme'
import Counter from './Counter'

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

describe('Counter component', () => {


it('should display count', () => {
const { p } = setup()
expect(p.text()).toMatch(/^Clicked: 0 times/)
})

it('first button should call onIncrement', () => {


const { buttons, actions } = setup()
buttons.at(0).simulate('click')
expect(actions.onIncrement).toBeCalled()
})

it('second button should call onDecrement', () => {


const { buttons, actions } = setup()
buttons.at(1).simulate('click')
expect(actions.onDecrement).toBeCalled()
})

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()
})

it('third button should call onIncrement if the counter is odd', () => {


const { buttons, actions } = setup(43)
buttons.at(2).simulate('click')
expect(actions.onIncrement).toBeCalled()
})

it('third button should call onIncrement if the counter is


odd and negative', () => {
const { buttons, actions } = setup(-43)
buttons.at(2).simulate('click')
expect(actions.onIncrement).toBeCalled()
})

it('fourth button should call onIncrement in a second', (done) => {


const { buttons, actions } = setup()
buttons.at(3).simulate('click')
setTimeout(() => {
expect(actions.onIncrement).toBeCalled()
done()
}, 1000)
})
})
Step 4: Reducers
This is a reducer, a function that takes a current state value and an action object
describing “what happened”, and returns a new state value. A reducer’s function
signature is: (state, action) => newState. it means a reducer function takes two
parameters state and action. The Redux state should contain only plain JS objects,
arrays, and primitives. The root state value is usually an object. It’s important that you
should not mutate the state object, but return a new object if the state changes. You
can use any conditional logic you want in a reducer. In this example, we use a switch
statement, but it’s not required.
index.js
• Javascript
export default (state = 0, action) => {
switch (action.type) {
case 'INCREMENT':
return state + 1
case 'DECREMENT':
return state - 1
default:
return state
}
}
Index.spec.js
• Javascript
import counter from './index'

describe('reducers', () => {
describe('counter', () => {
it('should provide the initial state', () => {
expect(counter(undefined, {})).toBe(0)
})

it('should handle INCREMENT action', () => {


expect(counter(1, { type: 'INCREMENT' })).toBe(2)
})

it('should handle DECREMENT action', () => {


expect(counter(1, { type: 'DECREMENT' })).toBe(0)
})

it('should ignore unknown actions', () => {


expect(counter(1, { type: 'unknown' })).toBe(1)
})
})
})
Step 5: Store
All container components need access to the Redux Store to subscribe to it. For this,
we need to pass it(store) as a prop to every container component. However, it gets
tedious. So we recommend using a special React Redux component called which
makes the store available to all container components without passing it explicitly. It
is used once when you render the root component.
index.js
• Javascript
import React from 'react'
import ReactDOM from 'react-dom'
import { createStore } from 'redux'
import Counter from './components/Counter'
import counter from './reducers'

const store = createStore(counter)


const rootEl = document.getElementById('root')

const render = () => ReactDOM.render(


<Counter
value={store.getState()}
onIncrement={() => store.dispatch({ type: 'INCREMENT' })}
onDecrement={() => store.dispatch({ type: 'DECREMENT' })}
/>,
rootEl
)

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.

Using CSS Modules In React :

Using 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.

npx create-react-app my-app --template typescript


Since I started utilizing React Typescript with CSS Modules, I have run into this problem. To
begin using CSS Modules in a React Project, you don’t need to import or install any third-
party libraries. You must import the CSS module before utilizing its React components.

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.

Using the dot notation:

<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:

const buttonClasses = classes.myBtn+ " " + classes.extra_classes;


I believe everything is clear. These are the fundamental concepts of a plain vanilla Javascript
object.

Pros and Cons of CSS Modules :


CSS Modules have several pros:

• 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.

What are the differences between class and functional


components?

Functional Components Class Components

A functional component is just a plain A class component requires you to extend


JavaScript pure function that accepts props from React. Component and create a
as an argument and returns a React render function that returns a React
element(JSX). element.

It must have the render() method returning


There is no render method used in
JSX (which is syntactically similar to
functional components.
HTML)

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.

Also known as Stateless components as they


simply accept data and display them in Also known as Stateful components
some form, they are mainly responsible for because they implement logic and state.
rendering UI.

React lifecycle methods (for example, React lifecycle methods can be used
componentDidMount) cannot be used in inside class components (for example,
functional components. componentDidMount).

It requires different syntax inside a class


component to implement hooks.
Hooks can be easily used in functional
Example:
components to make them Stateful.
constructor(props) {
Example:
super(props);
const [name,SetName]= React.useState(' ')
this.state = {name: ' '}
}

Constructor is used as it needs to store


Constructors ar e not used.
state.

React virtual DOM :


What is Virtual DOM?

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.

How does virtual DOM actually make things faster?

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.

How virtual DOM Helps React?

In React, everything is treated as a component be it a functional component or class


component. A component can contain a state. Whenever the state of any component is
changed react updates its Virtual DOM tree. Though it may sound like it is ineffective
the cost is not much significant as updating the virtual DOM doesn’t take much time.
React maintains two Virtual DOM at each time, one contains the updated Virtual
DOM and one which is just the pre-update version of this updated Virtual DOM. Now
it compares the pre-update version with the updated Virtual DOM and figures out
what exactly has changed in the DOM like which components have been changed.
This process of comparing the current Virtual DOM tree with the previous one is
known as ‘diffing’. Once React finds out what exactly has changed then it updates
those objects only, on real DOM.
React uses something called batch updates to update the real DOM. It just means that
the changes to the real DOM are sent in batches instead of sending any update for a
single change in the state of a component.
We have seen that the re-rendering 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

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 .

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy