Full Stack Unit 4
Full Stack Unit 4
React JS: ReactDOM - JSX - Components - Properties – Fetch API - State and Lifecycle -
-JS Localstorage - Events - Lifting State Up - Composition and Inheritance
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.
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.
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.
React Environment
Setup Pre-requisite
for ReactJS
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.
2
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.
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.
1. javatpoint@root:~/>npm install -g create-react-app
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.
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
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
JSX
Components
One-way Data Binding
Virtual DOM
Simplicity
Performance
JSX
5
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
Virtual DOM
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
Advantage of ReactJS
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.
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
4. Performance Enhancement
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
7
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.
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
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
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.
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
8
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?
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:
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.
9
Syntax:
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(comp
onent)
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.
Syntax:
ReactDOM.unmountComponentAtNode(con
tainer)
Parameters: This method takes a single parameter container which expects the
DOM container from which the React component has to be removed.
10
Return Type: This function returns true on success otherwise false.
hydrate() Function
Syntax:
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
Syntax:
ReactDOM.createPortal(child, container)
JSX
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
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."
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
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
13
Example
Output:
JavaTpoint
This website contains the best CS tutorials.
Example
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
14
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
Output:
Example
15
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.
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.
16
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. }
Class Components
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.
Output:
19
Properties
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.
Ex
ple
Ap
p.j
Main.js
Default Props
Ex
ple
Ap
p.j
Main.js
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
21
be shown in the below example.
Ex
ple
Ap
p.j
Main.js
Fetch API
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.
react-app MY-APP
Step 2: Change your directory and enter your main folder charting as
cd MY-APP
https://jsonplaceholder.typicode.com/
users
Step 4: Write code in App.js to fetch data from API and we are
using fetch function.
23
Project
Structure
Example:
// Constructor
constructor(p
rops) {
super(props);
this.st
ate
={
ite
ms:
[],
DataisLoaded: false
};
}
// ComponentDidMount is used to
// execute the code
componentDidMo
unt() {
fetch(
"https://jsonplaceholder.typicode.com/users")
.then((res) => res.json())
.then((jso
n) => {
this.set
State({
items:
json,
24
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>
);
}
}
.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;
}
25
.App-link
{ color:
#61dafb;
}
@keyframes App-
logo-spin { from {
transform: rotate(0deg);
}
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/
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.
26
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 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.
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
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.
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
28
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.
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
29
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
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
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
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');
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
31
user’s computer.
Example
App.jsx
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
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.
33
Adding Events
onClick="shoot()".
React:
HTML:
return (
<button onClick={shoot}>Take the shot!</button>
);}
const root =
ReactDOM.createRoot(document.getElementById('root'));
root.render(<Football />);
Passing Arguments
Example:
return (
<button onClick={() => shoot("Goal!")}>Take the shot!</button>
34
);}
const root =
ReactDOM.createRoot(document.getElementById('root'));
root.render(<Football />);
React Event Object
Event handlers have access to the React event that triggered the
Example:
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.
A
/\
B C
Where A is the parent of B and C. In this case, If there is some Data only in
35
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).
Problem: Let’s Implement this with a simple but general example. We are
considering the second example.
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:
After:
Filename- A.js:
handleTextChange(newT
ext) {
this.setState({text:
newText});
}
render()
{ return
(
<React.Fragment>
<B text={this.state.text}
handleTextChange={this.handleTextCha
nge}/>
<C text={this.state.text} />
</React.Fragment>
);
}
}
export default A;
Filename- B.js:
constructor(p
rops) {
super(prop
s);
this.handleTextChange = this.handleTextChange.bind(this);
}
handleTextChange(e){
this.props.handleTextChange(e.target.
value);
}
render() {
return (
<input value={this.props.text}
onChange={this.handleTextCha
nge} />
);
}
}
export default B;
37
Filename- C.js:
render() {
return (
<h3>Output: {this.props.text}</h3>
);
}
}
export default C;
Example to understand it −
Inheritance
This sis simple to just input the name. We will have two more components to
create and update the username field.
38
React.Component {
render() {
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.r
ender( (<div>
< CreateUserName />
< UpdateUserName />
</div>), document.getElementById('root'));
Composition
Use of composition is simpler than inheritance and easy to maintain the complexity.
40