0% found this document useful (0 votes)
6 views40 pages

MC4201 Unit 4

Uploaded by

dhanekaa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views40 pages

MC4201 Unit 4

Uploaded by

dhanekaa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

lOMoARcPSD|20794328

Department of Master of Computer Applications


Unit - 4
ADVANCED CLIENT SIDE PROGRAMMING

React JS

ReactJS is a declarative, efficient, and flexible JavaScript library for building reusable
UI components. It is an open-source, component-based front end library responsible
only for the view layer of the application. It was created by Jordan Walke, who was
a software engineer at Facebook. It was initially developed and maintained by
Facebook and was later used in its products like WhatsApp & Instagram. Facebook
developed ReactJS in 2011 in its newsfeed section, but it was released to the public in
the month of May 2013.

Today, most of the websites are built using MVC (model view controller) architecture.
In MVC architecture, React is the 'V' which stands for view, whereas the architecture
is provided by the Redux or Flux.

A ReactJS application is made up of multiple components, each component


responsible for outputting a small, reusable piece of HTML code. The components are
the heart of all React applications. These Components can be nested with other
components to allow complex applications to be built of simple building blocks.
ReactJS uses virtual DOM based mechanism to fill data in HTML DOM. The virtual
DOM works fast as it only changes individual DOM elements instead of reloading
complete DOM every time.

To create React app, we write React components that correspond to various elements.
We organize these components inside higher level components which define the
application structure. For example, we take a form that consists of many elements like
input fields, labels, or buttons. We can write each element of the form as React
components, and then we combine it into a higher-level component, i.e., the form
component itself. The form components would specify the structure of the form along
with elements inside of it.

Why learn ReactJS?

Today, many JavaScript frameworks are available in the market(like angular, node),
but still, React came into the market and gained popularity amongst them. The
previous frameworks follow the traditional data flow structure, which uses the DOM
(Document Object Model). DOM is an object which is created by the browser each
time a web page is loaded. It dynamically adds or removes the data at the back end
and when any modifications were done, then each time a new DOM is created for the
same page. This repeated creation of DOM makes unnecessary memory wastage and
reduces the performance of the application.

Therefore, a new technology ReactJS framework invented which remove this


drawback. ReactJS allows you to divide your entire application into various
components. ReactJS still used the same traditional data flow, but it is not directly
operating on the browser's Document Object Model (DOM) immediately; instead, it

Downloaded by V MERIN SHOBI ([email protected])


lOMoARcPSD|20794328

operates on a virtual DOM. It means rather than manipulating the document in a


browser after changes to our data, it resolves changes on a DOM built and run entirely
in memory. After the virtual DOM has been updated, React determines what changes
made to the actual browser's DOM. The React Virtual DOM exists entirely in
memory and is a representation of the web browser's DOM. Due to this, when we
write a React component, we did not write directly to the DOM; instead, we are
writing virtual components that react will turn into the DOM.

React Environment Setup

Pre-requisite for ReactJS

1. NodeJS and NPM


2. React and React DOM
3. Webpack
4. Babel

Ways to install ReactJS

There are two ways to set up an environment for successful ReactJS application. They
are given below.

1. Using the npm command


2. Using the create-react-app command

1. Using the npm command

Install React and React DOM

Create a root folder with the name reactApp on the desktop or where you want. Here,
we create it on the desktop. You can create the folder directly or using the command
given below.

Now, you need to create a package.json file. To create any module, it is required to
generate a package.json file in the project folder. To do this, you need to run the
following command as shown in the below image.

Downloaded by V MERIN SHOBI ([email protected])


lOMoARcPSD|20794328

After creating a package.json file, you need to install react and its DOM packages
using the following npm command in the terminal window as shown in the below
image.

You can also use the above command separately which can be shown as below.

1. javatpoint@root:~/Desktop/reactApp>npm install react --save


2. javatpoint@root:~/Desktop/reactApp>npm install react-dom --save

2. Using the create-react-app command

If you do not want to install react by using webpack and babel, then you can choose
create-react-app to install react. The 'create-react-app' is a tool maintained by
Facebook itself.

Install React

You can install React using npm package manager by using the below command.
There is no need to worry about the complexity of React installation. The
create-react-app npm package will take care of it.

Downloaded by V MERIN SHOBI ([email protected])


lOMoARcPSD|20794328

1. javatpoint@root:~/>npm install -g create-react-app

Create a new React project

After the installation of React, you can create a new react project using
create-react-app command. Here, I choose jtp-reactapp name for my project.

1. javatpoint@root:~/>create-react-app jtp-reactapp

NOTE: You can combine the above two steps in a single command using npx.
The npx is a package runner tool that comes with npm 5.2 and above version.

1. javatpoint@root:~/>npx create-react-app jtp-reactapp

The above command will install the react and create a new project with the name
jtp-reactapp. This app contains the following sub-folders and files by default which
can be shown in the below image.

Now, to get started, open the src folder and make changes in your desired file. By
default, the src folder contain the following files shown in below image.

For example, I will open App.js and make changes in its code which are shown
below.

App.js

1. import React from 'react';


2. import logo from './logo.svg';
3. import './App.css';
4. function App() {
5. return (
6. <div className="App">
7. <header className="App-header">
8. <img src={logo} className="App-logo" alt="logo" />
9. <p>
10. Welcome To JavaTpoint.

Downloaded by V MERIN SHOBI ([email protected])


lOMoARcPSD|20794328

11. <p>To get started, edit src/App.js and save to reload.</p>


12. </p>
13. <a
14. className="App-link"
15. href="https://reactjs.org"
16. target="_blank"
17. rel="noopener noreferrer"
18. >
19. Learn React
20. </a>
21. </header>
22. </div>
23. );
24. }
25. export default App;

Running the Server

After completing the installation process, you can start the server by running the
following command.

1. javatpoint@root:~/Desktop>cd jtp-reactapp
2. javatpoint@root:~/Desktop/jtp-reactapp>npm start

It will show the port number which we need to open in the browser. After we open it,
you will see the following output.

React Features

Currently, ReactJS gaining quick popularity as the best JavaScript framework among
web developers. It is playing an essential role in the front-end ecosystem. The
important features of ReactJS are as following.

 JSX
 Components
 One-way Data Binding
 Virtual DOM

Downloaded by V MERIN SHOBI ([email protected])


lOMoARcPSD|20794328

 Simplicity
 Performance

JSX

JSX stands for JavaScript XML. It is a JavaScript syntax extension. Its an XML or
HTML like syntax used by ReactJS. This syntax is processed into JavaScript calls of
React Framework. It extends the ES6 so that HTML like text can co-exist with
JavaScript react code. It is not necessary to use JSX, but it is recommended to use in
ReactJS.

Components

ReactJS is all about components. ReactJS application is made up of multiple


components, and each component has its own logic and controls. These components
can be reusable which help you to maintain the code when working on larger scale
projects.

One-way Data Binding

ReactJS is designed in such a manner that follows unidirectional data flow or one-way
data binding. The benefits of one-way data binding give you better control throughout
the application. If the data flow is in another direction, then it requires additional
features. It is because components are supposed to be immutable and the data within
them cannot be changed. Flux is a pattern that helps to keep your data unidirectional.
This makes the application more flexible that leads to increase efficiency.

Virtual DOM

A virtual DOM object is a representation of the original DOM object. It works like a
one-way data binding. Whenever any modifications happen in the web application,
the entire UI is re-rendered in virtual DOM representation. Then it checks the
difference between the previous DOM representation and new DOM. Once it has
done, the real DOM will update only the things that have actually changed. This
makes the application faster, and there is no wastage of memory.

Simplicity

ReactJS uses JSX file which makes the application simple and to code as well as
understand. We know that ReactJS is a component-based approach which makes the
code reusable as your need. This makes it simple to use and learn.

Performance

ReactJS is known to be a great performer. This feature makes it much better than
other frameworks out there today. The reason behind this is that it manages a virtual
DOM. The DOM is a cross-platform and programming API which deals with HTML,
XML or XHTML. The DOM exists entirely in memory. Due to this, when we create a
component, we did not write directly to the DOM. Instead, we are writing virtual
components that will turn into the DOM leading to smoother and faster performance.

Downloaded by V MERIN SHOBI ([email protected])


lOMoARcPSD|20794328

Pros and Cons of ReactJS

Today, ReactJS is the highly used open-source JavaScript Library. It helps in creating
impressive web apps that require minimal effort and coding. The main objective of
ReactJS is to develop User Interfaces (UI) that improves the speed of the apps. There
are important pros and cons of ReactJS given as following:

Advantage of ReactJS

1. Easy to Learn and USe

ReactJS is much easier to learn and use. It comes with a good supply of
documentation, tutorials, and training resources. Any developer who comes from a
JavaScript background can easily understand and start creating web apps using React
in a few days. It is the V(view part) in the MVC (Model-View-Controller) model, and
referred to as ?one of the JavaScript frameworks.? It is not fully featured but has the
advantage of open-source JavaScript User Interface(UI) library, which helps to
execute the task in a better manner.

2. Creating Dynamic Web Applications Becomes Easier

To create a dynamic web application specifically with HTML strings was tricky
because it requires a complex coding, but React JS solved that issue and makes it
easier. It provides less coding and gives more functionality. It makes use of the
JSX(JavaScript Extension), which is a particular syntax letting HTML quotes and
HTML tag syntax to render particular subcomponents. It also supports the building of
machine-readable codes.

3. Reusable Components

A ReactJS web application is made up of multiple components, and each component


has its own logic and controls. These components are responsible for outputting a
small, reusable piece of HTML code which can be reused wherever you need them.
The reusable code helps to make your apps easier to develop and maintain. These
Components can be nested with other components to allow complex applications to be
built of simple building blocks. ReactJS uses virtual DOM based mechanism to fill
data in HTML DOM. The virtual DOM works fast as it only changes individual DOM
elements instead of reloading complete DOM every time.

4. Performance Enhancement

ReactJS improves performance due to virtual DOM. The DOM is a cross-platform


and programming API which deals with HTML, XML or XHTML. Most of the
developers faced the problem when the DOM was updated, which slowed down the
performance of the application. ReactJS solved this problem by introducing virtual
DOM. The React Virtual DOM exists entirely in memory and is a representation of
the web browser's DOM. Due to this, when we write a React component, we did not
write directly to the DOM. Instead, we are writing virtual components that react will
turn into the DOM, leading to smoother and faster performance.

Downloaded by V MERIN SHOBI ([email protected])


lOMoARcPSD|20794328

5. The Support of Handy Tools

React JS has also gained popularity due to the presence of a handy set of tools. These
tools make the task of the developers understandable and easier. The React Developer
Tools have been designed as Chrome and Firefox dev extension and allow you to
inspect the React component hierarchies in the virtual DOM. It also allows you to
select particular components and examine and edit their current props and state.

6.Known to be SEO Friendly

Traditional JavaScript frameworks have an issue in dealing with SEO. The search
engines generally having trouble in reading JavaScript-heavy applications. Many web
developers have often complained about this problem. ReactJS overcomes this
problem that helps developers to be easily navigated on various search engines. It is
because React.js applications can run on the server, and the virtual DOM will be
rendering and returning to the browser as a regular web page.

7. The Benefit of Having JavaScript Library

Today, ReactJS is choosing by most of the web developers. It is because it is offering


a very rich JavaScript library. The JavaScript library provides more flexibility to the
web developers to choose the way they want.

8. Scope for Testing the Codes

ReactJS applications are extremely easy to test. It offers a scope where the developer
can test and debug their codes with the help of native tools.

Disadvantage of ReactJS

1. The high pace of development

The high pace of development has an advantage and disadvantage both. In case of
disadvantage, since the environment continually changes so fast, some of the
developers not feeling comfortable to relearn the new ways of doing things regularly.
It may be hard for them to adopt all these changes with all the continuous updates.
They need to be always updated with their skills and learn new ways of doing things.

2. Poor Documentation

It is another cons which are common for constantly updating technologies. React
technologies updating and accelerating so fast that there is no time to make proper
documentation. To overcome this, developers write instructions on their own with the
evolving of new releases and tools in their current projects.

3. View Part

ReactJS Covers only the UI Layers of the app and nothing else. So you still need to
choose some other technologies to get a complete tooling set for development in the
project.

Downloaded by V MERIN SHOBI ([email protected])


lOMoARcPSD|20794328

4. JSX as a barrier

ReactJS uses JSX. It's a syntax extension that allows HTML with JavaScript mixed
together. This approach has its own benefits, but some members of the development
community consider JSX as a barrier, especially for new developers. Developers
complain about its complexity in the learning curve.

ReactDOM

ReactJS is a library to build active User Interfaces thus rendering is one of the integral
parts of ReactJS. React provides the developers with a package react-dom a.k.a
ReactDOM to access and modify the DOM. Let’s see in brief what is the need of
having the package.

What is DOM?

DOM, abbreviated as Document Object Model, is a World Wide Web Consortium


standard logical representation of any webpage. In easier words, DOM is a tree-like
structure that contains all the elements and it’s properties of a website as its nodes.
DOM provides a language-neutral interface that allows accessing and updating of the
content of any element of a webpage.

Before React, Developers directly manipulated the DOM elements which resulted in
frequent DOM manipulation, and each time an update was made the browser had to
recalculate and repaint the whole view according to the particular CSS of the page,
which made the total process to consume a lot of time. As a betterment, React brought
into the scene the virtual DOM. The Virtual DOM can be referred to as a copy of the
actual DOM representation that is used to hold the updates made by the user and
finally reflect it over to the original Browser DOM at once consuming much lesser
time.

What is ReactDOM?

ReactDOM is a package that provides DOM specific methods that can be used at the
top level of a web app to enable an efficient way of managing DOM elements of the
web page. ReactDOM provides the developers with an API containing the following
methods and a few more.

 render()
 findDOMNode()
 unmountComponentAtNode()
 hydrate()
 createPortal()

Pre-requisite: To use the ReactDOM in any React web app we must first import
ReactDOM from the react-dom package by using the following code snippet:

import ReactDOM from 'react-dom'

Downloaded by V MERIN SHOBI ([email protected])


lOMoARcPSD|20794328

render() Function

This is one of the most important methods of ReactDOM. This function is used to
render a single React Component or several Components wrapped together in a
Component or a div element. This function uses the efficient methods of React for
updating the DOM by being able to change only a subtree, efficient diff methods, etc.

Syntax:

ReactDOM.render(element, container, callback)

Parameters: This method can take a maximum of three parameters as described


below.

 element: This parameter expects a JSX expression or a React Element to be


rendered.
 container: This parameter expects the container in which the element has to
be rendered.
 callback: This is an optional parameter that expects a function that is to be
executed once the render is complete.

Return Type: This function returns a reference to the component or null if a stateless
component was rendered.

findDOMNode() Function

This function is generally used to get the DOM node where a particular React
component was rendered. This method is very less used like the following can be
done by adding a ref attribute to each component itself.

Syntax:

ReactDOM.findDOMNode(component)

Parameters: This method takes a single parameter component that expects a React
Component to be searched in the Browser DOM.

Return Type: This function returns the DOM node where the component was
rendered on success otherwise null.

unmountComponentAtNode() Function

This function is used to unmount or remove the React Component that was rendered
to a particular container. As an example, you may think of a notification component,
after a brief amount of time it is better to remove the component making the web page
more efficient.

10

Downloaded by V MERIN SHOBI ([email protected])


lOMoARcPSD|20794328

Syntax:

ReactDOM.unmountComponentAtNode(container)

Parameters: This method takes a single parameter container which expects the DOM
container from which the React component has to be removed.

Return Type: This function returns true on success otherwise false.

hydrate() Function

This method is equivalent to the render() method but is implemented while using
server-side rendering.

Syntax:

ReactDOM.hydrate(element, container, callback)

Parameters: This method can take a maximum of three parameters as described


below.

 element: This parameter expects a JSX expression or a React Component to


be rendered.
 container: This parameter expects the container in which the element has to
be rendered.
 callback: This is an optional parameter that expects a function that is to be
executed once the render is complete.

Return Type: This function attempts to attach event listeners to the existing markup
and returns a reference to the component or null if a stateless component was
rendered.

createPortal() Function

Usually, when an element is returned from a component’s render method, it’s


mounted on the DOM as a child of the nearest parent node which in some cases may
not be desired. Portals allow us to render a component into a DOM node that resides
outside the current DOM hierarchy of the parent component.

Syntax:

ReactDOM.createPortal(child, container)

Parameters: This method takes two parameters as described below.

 child: This parameter expects a JSX expression or a React Component to be


rendered.

11

Downloaded by V MERIN SHOBI ([email protected])


lOMoARcPSD|20794328

 container: This parameter expects the container in which the element has to
be rendered.

Return Type: This function returns nothing.

JSX

JSX(JavaScript Extension), is a React extension which allows writing JavaScript code


that looks like HTML. In other words, JSX is an HTML-like syntax used by React
that extends ECMAScript so that HTML-like syntax can co-exist with
JavaScript/React code. The syntax is used by preprocessors (i.e., transpilers like
babel) to transform HTML-like syntax into standard JavaScript objects that a
JavaScript engine will parse.

JSX provides you to write HTML/XML-like structures (e.g., DOM-like tree structures)
in the same file where you write JavaScript code, then preprocessor will transform
these expressions into actual JavaScript code. Just like XML/HTML, JSX tags have a
tag name, attributes, and children.

Example

Here, we will write JSX syntax in JSX file and see the corresponding JavaScript code
which transforms by preprocessor(babel).

JSX File

1. <div>Hello JavaTpoint</div>

Corresponding Output

1. React.createElement("div", null, "Hello JavaTpoint");

The above line creates a react element and passing three arguments inside where
the first is the name of the element which is div, second is the attributes passed in the
div tag, and last is the content you pass which is the "Hello JavaTpoint."

Why use JSX?

 It is faster than regular JavaScript because it performs optimization while


translating the code to JavaScript.
 Instead of separating technologies by putting markup and logic in separate
files, React uses components that contain both. We will learn components in a
further section.
 It is type-safe, and most of the errors can be found at compilation time.
 It makes easier to create templates.

12

Downloaded by V MERIN SHOBI ([email protected])


lOMoARcPSD|20794328

Nested Elements in JSX

To use more than one element, you need to wrap it with one container element. Here,
we use div as a container element which has three nested elements inside it.

App.JSX

1. import React, { Component } from 'react';


2. class App extends Component{
3. render(){
4. return(
5. <div>
6. <h1>JavaTpoint</h1>
7. <h2>Training Institutes</h2>
8. <p>This website contains the best CS tutorials.</p>
9. </div>
10. );
11. }
12. }
13. export default App;

Output:

JSX Attributes

JSX use attributes with the HTML elements same as regular HTML. JSX uses
camelcase naming convention for attributes rather than standard naming convention
of HTML such as a class in HTML becomes className in JSX because the class is
the reserved keyword in JavaScript. We can also use our own custom attributes in
JSX. For custom attributes, we need to use data- prefix. In the below example, we
have used a custom attribute data-demoAttribute as an attribute for the <p> tag.

Example

1. import React, { Component } from 'react';


2. class App extends Component{
3. render(){
4. return(
5. <div>

13

Downloaded by V MERIN SHOBI ([email protected])


lOMoARcPSD|20794328

6. <h1>JavaTpoint</h1>
7. <h2>Training Institutes</h2>
8. <p data-demoAttribute = "demo">This website contains the best CS tu
torials.</p>
9. </div>
10. );
11. }
12. }
13. export default App;

In JSX, we can specify attribute values in two ways:

1. As String Literals: We can specify the values of attributes in double quotes:

1. var element = <h2 className = "firstAttribute">Hello JavaTpoint</h2>;

Example

1. import React, { Component } from 'react';


2. class App extends Component{
3. render(){
4. return(
5. <div>
6. <h1 className = "hello" >JavaTpoint</h1>
7. <p data-demoAttribute = "demo">This website contains the best CS tut
orials.</p>
8. </div>
9. );
10. }
11. }
12. export default App;

Output:

JavaTpoint
This website contains the best CS tutorials.

2. As Expressions: We can specify the values of attributes as expressions using curly


braces {}:

1. var element = <h2 className = {varName}>Hello JavaTpoint</h2>;

Example

1. import React, { Component } from 'react';


2. class App extends Component{
3. render(){
4. return(
5. <div>
6. <h1 className = "hello" >{25+20}</h1>

14

Downloaded by V MERIN SHOBI ([email protected])


lOMoARcPSD|20794328

7. </div>
8. );
9. }
10. }
11. export default App;

Output:

45

JSX Comments

JSX allows us to use comments that begin with /* and ends with */ and wrapping
them in curly braces {} just like in the case of JSX expressions. Below example
shows how to use comments in JSX.

Example

1. import React, { Component } from 'react';


2. class App extends Component{
3. render(){
4. return(
5. <div>
6. <h1 className = "hello" >Hello JavaTpoint</h1>
7. {/* This is a comment in JSX */}
8. </div>
9. );
10. }
11. }
12. export default App;

JSX Styling

React always recommends to use inline styles. To set inline styles, you need to use
camelCase syntax. React automatically allows appending px after the number value
on specific elements. The following example shows how to use styling in the element.

Example

1. import React, { Component } from 'react';


2. class App extends Component{
3. render(){
4. var myStyle = {
5. fontSize: 80,
6. fontFamily: 'Courier',
7. color: '#003300'
8. }
9. return (
10. <div>
11. <h1 style = {myStyle}>www.javatpoint.com</h1>

15

Downloaded by V MERIN SHOBI ([email protected])


lOMoARcPSD|20794328

12. </div>
13. );
14. }
15. }
16. export default App;

Output:

Example

1. import React, { Component } from 'react';


2. class App extends Component{
3. render(){
4. var i = 5;
5. return (
6. <div>
7. <h1>{i == 1 ? 'True!' : 'False!'}</h1>
8. </div>
9. );
10. }
11. }
12. export default App;

Output:

False!

Components

Earlier, the developers write more than thousands of lines of code for developing a
single page application. These applications follow the traditional DOM structure, and
making changes in them was a very challenging task. If any mistake found, it
manually searches the entire application and update accordingly. The
component-based approach was introduced to overcome an issue. In this approach,
the entire application is divided into a small logical group of code, which is known as
components.

16

Downloaded by V MERIN SHOBI ([email protected])


lOMoARcPSD|20794328

A Component is considered as the core building blocks of a React application. It


makes the task of building UIs much easier. Each component exists in the same space,
but they work independently from one another and merge all in a parent component,
which will be the final UI of your application.

Every React component have their own structure, methods as well as APIs. They can
be reusable as per your need. For better understanding, consider the entire UI as a tree.
Here, the root is the starting component, and each of the other pieces becomes
branches, which are further divided into sub-branches.

In ReactJS, we have mainly two types of components. They are

1. Functional Components
2. Class Components

Functional Components

In React, function components are a way to write components that only contain a
render method and don't have their own state. They are simply JavaScript functions
that may or may not receive data as parameters. We can create a function that takes
props(properties) as input and returns what should be rendered. A valid functional
component can be shown in the below example.

1. function WelcomeMessage(props) {
2. return <h1>Welcome to the , {props.name}</h1>;
3. }

The functional component is also known as a stateless component because they do not
hold or manage state. It can be explained in the below example.

17

Downloaded by V MERIN SHOBI ([email protected])


lOMoARcPSD|20794328

Example

1. import React, { Component } from 'react';


2. class App extends React.Component {
3. render() {
4. return (
5. <div>
6. <First/>
7. <Second/>
8. </div>
9. );
10. }
11. }
12. class First extends React.Component {
13. render() {
14. return (
15. <div>
16. <h1>JavaTpoint</h1>
17. </div>
18. );
19. }
20. }
21. class Second extends React.Component {
22. render() {
23. return (
24. <div>
25. <h2>www.javatpoint.com</h2>
26. <p>This websites contains the great CS tutorial.</p>
27. </div>
28. );
29. }
30. }
31. export default App;

Output:

18

Downloaded by V MERIN SHOBI ([email protected])


lOMoARcPSD|20794328

Class Components

Class components are more complex than functional components. It requires you to
extend from React. Component and create a render function which returns a React
element. You can pass data from one class to other class components. You can create
a class by defining a class that extends Component and has a render function. Valid
class component is shown in the below example.

1. class MyComponent extends React.Component {


2. render() {
3. return (
4. <div>This is main component.</div>
5. );
6. }
7. }

The class component is also known as a stateful component because they can hold or
manage local state. It can be explained in the below example.

Example

In this example, we are creating the list of unordered elements, where we will
dynamically insert StudentName for every object from the data array. Here, we are
using ES6 arrow syntax (=>) which looks much cleaner than the old JavaScript syntax.
It helps us to create our elements with fewer lines of code. It is especially useful when
we need to create a list with a lot of items.

1. import React, { Component } from 'react';


2. class App extends React.Component {
3. constructor() {
4. super();
5. this.state = {
6. data:
7. [
8. {
9. "name":"Abhishek"
10. },
11. {
12. "name":"Saharsh"
13. },
14. {
15. "name":"Ajay"
16. }
17. ]
18. }
19. }
20. render() {
21. return (
22. <div>
23. <StudentName/>

19

Downloaded by V MERIN SHOBI ([email protected])


lOMoARcPSD|20794328

24. <ul>
25. {this.state.data.map((item) => <List data = {item} />)}
26. </ul>
27. </div>
28. );
29. }
30. }
31. class StudentName extends React.Component {
32. render() {
33. return (
34. <div>
35. <h1>Student Name Detail</h1>
36. </div>
37. );
38. }
39. }
40. class List extends React.Component {
41. render() {
42. return (
43. <ul>
44. <li>{this.props.data.name}</li>
45. </ul>
46. );
47. }
48. }
49. export default App;

Output:

Properties

Props stand for "Properties." They are read-only components. It is an object which
stores the value of attributes of a tag and work similar to the HTML attributes. It gives
a way to pass data from one component to other components. It is similar to function
arguments. Props are passed to the component in the same way as arguments passed
in a function.

20

Downloaded by V MERIN SHOBI ([email protected])


lOMoARcPSD|20794328

Props are immutable so we cannot modify the props from inside the component.
Inside the components, we can add attributes called props. These attributes are
available in the component as this.props and can be used to render dynamic data in
our render method.

When you need immutable data in the component, you have to add props to
reactDom.render() method in the main.js file of your ReactJS project and used it
inside the component in which you need. It can be explained in the below example.

Example

App.js

1. import React, { Component } from 'react';


2. class App extends React.Component {
3. render() {
4. return (
5. <div>
6. <h1> Welcome to { this.props.name } </h1>
7. <p> <h4> Javatpoint is one of the best Java training institute in Noida,
Delhi, Gurugram, Ghaziabad and Faridabad. </h4> </p>
8. </div>
9. );
10. }
11. }
12. export default App;

Main.js

1. import React from 'react';


2. import ReactDOM from 'react-dom';
3. import App from './App.js';
4.
5. ReactDOM.render(<App name = "JavaTpoint!!" />, document.getElementByI
d('app'));

Default Props

It is not necessary to always add props in the reactDom.render() element. You can
also set default props directly on the component constructor. It can be explained in
the below example.

Example

App.js

1. import React, { Component } from 'react';


2. class App extends React.Component {
3. render() {
4. return (

21

Downloaded by V MERIN SHOBI ([email protected])


lOMoARcPSD|20794328

5. <div>
6. <h1>Default Props Example</h1>
7. <h3>Welcome to {this.props.name}</h3>
8. <p>Javatpoint is one of the best Java training institute in Noida, Delhi,
Gurugram, Ghaziabad and Faridabad.</p>
9. </div>
10. );
11. }
12. }
13. App.defaultProps = {
14. name: "JavaTpoint"
15. }
16. export default App;

Main.js

1. import React from 'react';


2. import ReactDOM from 'react-dom';
3. import App from './App.js';
4.
5. ReactDOM.render(<App/>, document.getElementById('app'));

State and Props

It is possible to combine both state and props in your app. You can set the state in the
parent component and pass it in the child component using props. It can be shown in
the below example.

Example

App.js

1. import React, { Component } from 'react';


2. class App extends React.Component {
3. constructor(props) {
4. super(props);
5. this.state = {
6. name: "JavaTpoint",
7. }
8. }
9. render() {
10. return (
11. <div>
12. <JTP jtpProp = {this.state.name}/>
13. </div>
14. );
15. }
16. }
17. class JTP extends React.Component {
18. render() {

22

Downloaded by V MERIN SHOBI ([email protected])


lOMoARcPSD|20794328

19. return (
20. <div>
21. <h1>State & Props Example</h1>
22. <h3>Welcome to {this.props.jtpProp}</h3>
23. <p>Javatpoint is one of the best Java training institute in Noida, Delhi,
Gurugram, Ghaziabad and Faridabad.</p>
24. </div>
25. );
26. }
27. }
28. export default App;

Main.js

1. import React from 'react';


2. import ReactDOM from 'react-dom';
3. import App from './App.js';
4.
5. ReactDOM.render(<App/>, document.getElementById('app'));

Fetch API

ReactJS: ReactJS is a declarative, efficient, and flexible JavaScript library for


building user interfaces. It’s ‘V’ in MVC. ReactJS is an open-source,
component-based front-end library responsible only for the view layer of the
application. It is maintained by Facebook.

API: API is an abbreviation for Application Programming Interface which is a


collection of communication protocols and subroutines used by various programs to
communicate between them. A programmer can make use of various API tools to
make its program easier and simpler. Also, an API facilitates the programmers with
an efficient way to develop their software programs.

we will know how we fetch the data from API (Application Programming Interface).
For the data, we have used the API endpoint from
http://jsonplaceholder.typicode.com/users we have created the component in App.js
and styling the component in App.css. From the API we have target “id”, “name”,
“username”, “email” and fetch the data from API endpoints. Below is the stepwise
implementation of how we fetch the data from an API in react. We will use the fetch
function to get the data from the API.

Step by step implementation to fetch data from an api in react.

Step 1: Create React Project

npm create-react-app MY-APP

Step 2: Change your directory and enter your main folder charting as

23

Downloaded by V MERIN SHOBI ([email protected])


lOMoARcPSD|20794328

cd MY-APP

Step 3: API endpoint

https://jsonplaceholder.typicode.com/users

Step 4: Write code in App.js to fetch data from API and we are using fetch
function.

Project Structure: It will look the following.

Project Structure

Example:

import React from "react";


import './App.css';
class App extends React.Component {

// Constructor
constructor(props) {
super(props);

this.state = {
items: [],
DataisLoaded: false
};
}

// ComponentDidMount is used to
// execute the code
componentDidMount() {
fetch(
"https://jsonplaceholder.typicode.com/users")
.then((res) => res.json())
.then((json) => {
this.setState({
items: json,

24

Downloaded by V MERIN SHOBI ([email protected])


lOMoARcPSD|20794328

DataisLoaded: true
});
})
}
render() {
const { DataisLoaded, items } = this.state;
if (!DataisLoaded) return <div>
<h1> Pleses wait some time.... </h1> </div> ;

return (
<div className = "App">
<h1> Fetch data from an api in react </h1> {
items.map((item) => (
<ol key = { item.id } >
User_Name: { item.username },
Full_Name: { item.name },
User_Email: { item.email }
</ol>
))
}
</div>
);
}
}

export default App;

Write code in App.css for styling the app.js file.

.App {
text-align: center;
color: Green;
}
.App-header {
background-color: #282c34;
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-size: calc(10px + 2vmin);
color: white;
}
.App-link {
color: #61dafb;
}

@keyframes App-logo-spin {
from {
transform: rotate(0deg);

25

Downloaded by V MERIN SHOBI ([email protected])


lOMoARcPSD|20794328

}
to {
transform: rotate(360deg);
}
}

Step to run the application: Open the terminal and type the following command.

npm start

Output: Open the browser and our project is shown in the URL http://localhost:3000/

State and Lifecycle

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

26

Downloaded by V MERIN SHOBI ([email protected])


lOMoARcPSD|20794328

7. render() {
8. const bio = this.state.displayBio ? (
9. <div>
10. <p><h3>Javatpoint is one of the best Java training institute in Noid
a, Delhi, Gurugram, Ghaziabad and Faridabad. We have a team of experienced
Java developers and trainers from multinational companies to teach our camp
us 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.

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>

27

Downloaded by V MERIN SHOBI ([email protected])


lOMoARcPSD|20794328

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 exp
erienced Java developers and trainers from multinational companies to teach o
ur campus students.</h4></p>
20. <button onClick={this.toggleDisplayBio}> Show Less </bu
tton>
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;

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.

React Component Life-Cycle

In ReactJS, every component creation process involves various lifecycle methods.


These lifecycle methods are termed as component's lifecycle. These lifecycle methods
are not very complicated and called at various points during a component's life. The
lifecycle of the component is divided into four phases. They are:

1. Initial Phase
2. Mounting Phase
3. Updating Phase
4. Unmounting Phase

Each phase contains some lifecycle methods that are specific to the particular phase.
Let us discuss each of these phases one by one.

1. Initial Phase

It is the birth phase of the lifecycle of a ReactJS component. Here, the component
starts its journey on a way to the DOM. In this phase, a component contains the
default Props and initial State. These default properties are done in the constructor of
a component. The initial phase only occurs once and consists of the following
methods.

28

Downloaded by V MERIN SHOBI ([email protected])


lOMoARcPSD|20794328

 getDefaultProps()
It is used to specify the default value of this.props. It is invoked before the
creation of the component or any props from the parent is passed into it.
 getInitialState()
It is used to specify the default value of this.state. It is invoked before the
creation of the component.

2. Mounting Phase

In this phase, the instance of a component is created and inserted into the DOM. It
consists of the following methods.

 componentWillMount()
This is invoked immediately before a component gets rendered into the DOM.
In the case, when you call setState() inside this method, the component will
not re-render.
 componentDidMount()
This is invoked immediately after a component gets rendered and placed on
the DOM. Now, you can do any DOM querying operations.
 render()
This method is defined in each and every component. It is responsible for
returning a single root HTML node element. If you don't want to render
anything, you can return a null or false value.

3. Updating Phase

It is the next phase of the lifecycle of a react component. Here, we get new Props and
change State. This phase also allows to handle user interaction and provide
communication with the components hierarchy. The main aim of this phase is to
ensure that the component is displaying the latest version of itself. Unlike the Birth or
Death phase, this phase repeats again and again. This phase consists of the following
methods.

 componentWillRecieveProps()
It is invoked when a component receives new props. If you want to update the
state in response to prop changes, you should compare this.props and
nextProps to perform state transition by using this.setState() method.
 shouldComponentUpdate()
It is invoked when a component decides any changes/updation to the DOM. It
allows you to control the component's behavior of updating itself. If this
method returns true, the component will update. Otherwise, the component
will skip the updating.
 componentWillUpdate()
It is invoked just before the component updating occurs. Here, you can't
change the component state by invoking this.setState() method. It will not be
called, if shouldComponentUpdate() returns false.
 render()
It is invoked to examine this.props and this.state and return one of the
following types: React elements, Arrays and fragments, Booleans or null,
String and Number. If shouldComponentUpdate() returns false, the code

29

Downloaded by V MERIN SHOBI ([email protected])


lOMoARcPSD|20794328

inside render() will be invoked again to ensure that the component displays
itself properly.
 componentDidUpdate()
It is invoked immediately after the component updating occurs. In this method,
you can put any code inside this which you want to execute once the updating
occurs. This method is not invoked for the initial render.

4. Unmounting Phase

It is the final phase of the react component lifecycle. It is called when a component
instance is destroyed and unmounted from the DOM. This phase contains only one
method and is given below.

 componentWillUnmount()
This method is invoked immediately before a component is destroyed and
unmounted permanently. It performs any necessary cleanup related task such
as invalidating timers, event listener, canceling network requests, or cleaning
up DOM elements. If a component instance is unmounted, you cannot mount
it again.

Example

1. import React, { Component } from 'react';


2.
3. class App extends React.Component {
4. constructor(props) {
5. super(props);
6. this.state = {hello: "JavaTpoint"};
7. this.changeState = this.changeState.bind(this)
8. }
9. render() {
10. return (
11. <div>
12. <h1>ReactJS component's Lifecycle</h1>
13. <h3>Hello {this.state.hello}</h3>
14. <button onClick = {this.changeState}>Click Here!</button>
15. </div>
16. );
17. }
18. componentWillMount() {
19. console.log('Component Will MOUNT!')
20. }
21. componentDidMount() {
22. console.log('Component Did MOUNT!')
23. }
24. changeState(){
25. this.setState({hello:"All!!- Its a great reactjs tutorial."});
26. }
27. componentWillReceiveProps(newProps) {
28. console.log('Component Will Recieve Props!')

30

Downloaded by V MERIN SHOBI ([email protected])


lOMoARcPSD|20794328

29. }
30. shouldComponentUpdate(newProps, newState) {
31. return true;
32. }
33. componentWillUpdate(nextProps, nextState) {
34. console.log('Component Will UPDATE!');
35. }
36. componentDidUpdate(prevProps, prevState) {
37. console.log('Component Did UPDATE!')
38. }
39. componentWillUnmount() {
40. console.log('Component Will UNMOUNT!')
41. }
42. }

43. export default App;

When you click on the Click Here Button, you get the updated result which is shown
in the below screen.

JS Localstorage

LocalStorage is a web storage object to store the data on the user’s computer locally,
which means the stored data is saved across browser sessions and the data stored has
no expiration time.

Syntax

// To store data
localStorage.setItem('Name', 'Rahul');

// To retrieve data
localStorage.getItem('Name');

// To clear a specific item


localStorage.removeItem('Name');

// To clear the whole data stored in localStorage


localStorage.clear();

Set, retrieve and remove data in localStorage

In this example, we will build a React application which takes the username and
password from the user and stores it as an item in the localStorage of the user’s
computer.

31

Downloaded by V MERIN SHOBI ([email protected])


lOMoARcPSD|20794328

Example

App.jsx

import React, { useState } from 'react';

const App = () => {

const [name, setName] = useState('');


const [pwd, setPwd] = useState('');

const handle = () => {


localStorage.setItem('Name', name);
localStorage.setItem('Password', pwd);
};
const remove = () => {
localStorage.removeItem('Name');
localStorage.removeItem('Password');
};
return (
<div className="App">
<h1>Name of the user:</h1>
<input
placeholder="Name"
value={name}
onChange={(e) => setName(e.target.value)}
/>
<h1>Password of the user:</h1>
<input
type="password"
placeholder="Password"
value={pwd}
onChange={(e) => setPwd(e.target.value)}
/>
<div>
<button onClick={handle}>Done</button>
</div>
{localStorage.getItem('Name') && (
<div>
Name: <p>{localStorage.getItem('Name')}</p>
</div>
)}
{localStorage.getItem('Password') && (
<div>
Password: <p>{localStorage.getItem('Password')}</p>
</div>
)}
<div>
<button onClick={remove}>Remove</button>
</div>

32

Downloaded by V MERIN SHOBI ([email protected])


lOMoARcPSD|20794328

</div>
);
};
export default App;

In the above example, when the Done button is clicked, the handle function is
executed which will set the items in the localStorage of the user and display it. But
when the Remove button is clicked, the remove function is executed which will
remove the items from the localStorage.

Output

This will produce the following result.

Events

Just like HTML DOM events, React can perform actions based on user events.

React has the same events as HTML: click, change, mouseover etc.

Adding Events

React events are written in camelCase syntax:

33

Downloaded by V MERIN SHOBI ([email protected])


lOMoARcPSD|20794328

onClick instead of onclick.

React event handlers are written inside curly braces:

onClick={shoot} instead of onClick="shoot()".

React:

<button onClick={shoot}>Take the Shot!</button>

HTML:

<button onclick="shoot()">Take the Shot!</button>

Example:

Put the shoot function inside the Football component:

function Football() {
const shoot = () => {
alert("Great Shot!");
}

return (
<button onClick={shoot}>Take the shot!</button>
);}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Football />);

Passing Arguments

To pass an argument to an event handler, use an arrow function.

Example:

Send "Goal!" as a parameter to the shoot function, using arrow function:

function Football() {
const shoot = (a) => {
alert(a);
}

return (
<button onClick={() => shoot("Goal!")}>Take the shot!</button>
);}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Football />);

34

Downloaded by V MERIN SHOBI ([email protected])


lOMoARcPSD|20794328

React Event Object

Event handlers have access to the React event that triggered the function.

In our example the event is the "click" event.

Example:

Arrow Function: Sending the event object manually:

function Football() {
const shoot = (a, b) => {
alert(b.type);
/*
'b' represents the React event that triggered the function,
in this case the 'click' event
*/
}

return (
<button onClick={(event) => shoot("Goal!", event)}>Take the shot!</button>
);}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Football />);

Lifting State Up

Lifting up the State: As we know, every component in React has its own state.
Because of this sometimes data can be redundant and inconsistent. So, by Lifting up
the state we make the state of the parent component as a single source of truth and
pass the data of the parent in its children.

Time to use Lift up the State: If the data in “parent and children components” or in
“cousin components” is Not in Sync.

Example 1: If we have 2 components in our App. A -> B where, A is parent of B.


keeping the same data in both Component A and B might cause inconsistency of
data.

Example 2: If we have 3 components in our App.

A
/\
B C

Where A is the parent of B and C. In this case, If there is some Data only in
component B but, component C also wants that data. We know Component C cannot
access the data because a component can talk only to its parent or child (Not cousins).

35

Downloaded by V MERIN SHOBI ([email protected])


lOMoARcPSD|20794328

Problem: Let’s Implement this with a simple but general example. We are
considering the second example.

Complete File Structure:

Approach: To solve this, we will Lift the state of component B and component C to
component A. Make A.js as our Main Parent by changing the path of App in the
index.js file

Before:

import App from './App';

After:

import App from './A';

Filename- A.js:

import React,{ Component } from 'react';


import B from './B'
import C from './C'

class A extends Component {

36

Downloaded by V MERIN SHOBI ([email protected])


lOMoARcPSD|20794328

constructor(props) {
super(props);
this.handleTextChange = this.handleTextChange.bind(this);
this.state = {text: ''};
}

handleTextChange(newText) {
this.setState({text: newText});
}

render() {
return (
<React.Fragment>
<B text={this.state.text}
handleTextChange={this.handleTextChange}/>
<C text={this.state.text} />
</React.Fragment>
);
}
}

export default A;

Filename- B.js:

import React,{ Component } from 'react';

class B extends Component {

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

handleTextChange(e){
this.props.handleTextChange(e.target.value);
}

render() {
return (
<input value={this.props.text}
onChange={this.handleTextChange} />
);
}
}

export default B;

37

Downloaded by V MERIN SHOBI ([email protected])


lOMoARcPSD|20794328

Filename- C.js:

import React,{ Component } from 'react';

class C extends Component {

render() {
return (
<h3>Output: {this.props.text}</h3>
);
}
}

export default C;

Output: Now, component C can Access text in component B through component A.

Composition and Inheritance

Composition and inheritance are the approaches to use multiple components together
in React.js . This helps in code reuse. React recommend using composition instead of
inheritance as much as possible and inheritance should be used in very specific cases
only.

Example to understand it −

Let’s say we have a component to input username.

Inheritance

class UserNameForm extends React.Component {


render() {
return (
<div>
<input type="text" />
</div>
);
}}ReactDOM.render(
< UserNameForm />,
document.getElementById('root'));

This sis simple to just input the name. We will have two more components to create
and update the username field.

With the use of inheritance we will do it like −

class UserNameForm extends React.Component {


render() {

38

Downloaded by V MERIN SHOBI ([email protected])


lOMoARcPSD|20794328

return (
<div>
<input type="text" />
</div>
);
}}class CreateUserName extends UserNameForm {
render() {
const parent = super.render();
return (
<div>
{parent}
<button>Create</button>
</div>
)
}}class UpdateUserName extends UserNameForm {
render() {
const parent = super.render();
return (
<div>
{parent}
<button>Update</button>
</div>
)
}}ReactDOM.render(
(<div>
< CreateUserName />
< UpdateUserName />
</div>), document.getElementById('root'));

We extended the UserNameForm component and extracted its method in child


component using super.render();

Composition

class UserNameForm extends React.Component {


render() {
return (
<div>
<input type="text" />
</div>
);
}}class CreateUserName extends React.Component {
render() {
return (
<div>
< UserNameForm />
<button>Create</button>
</div>
)
}}class UpdateUserName extends React.Component {

39

Downloaded by V MERIN SHOBI ([email protected])


lOMoARcPSD|20794328

render() {
return (
<div>
< UserNameForm />
<button>Update</button>
</div>
)
}}ReactDOM.render(
(<div>
<CreateUserName />
<UpdateUserName />
</div>), document.getElementById('root'));

Use of composition is simpler than inheritance and easy to maintain the complexity.

40

Downloaded by V MERIN SHOBI ([email protected])

You might also like