Full Stack Web Development
Full Stack Web Development
React JS: ReactDOM - JSX - Components - Properties – Fetch API - State and Lifecycle - -JS Local storage –
Events - Lifting State Up - Composition and Inheritance
React JS Introduction
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.
What is React?
React, sometimes referred to as a frontend JavaScript framework, is a JavaScript library created by Facebook.
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
Simplicity
Performance
Applications
React app calls ReactDOM.render method by passing the user interface created using React component
(coded in either JSX or React element format) and the container to render the user interface.
ReactDOM.render processes the JSX or React element and emits Virtual DOM.
Virtual DOM will be merged and rendered into the container.
React library is just UI library and it does not enforce any particular pattern to write a complex
application. Developers are free to choose the design pattern of their choice. React community advocates
certain design pattern. One of the patterns is Flux pattern. React library also provides lot of concepts like
Higher Order component, Context, Render props, Refs etc., to write better code. React Hooks is evolving
concept to do state management in big projects. Let us try to understand the high level architecture of a
React application.
Requirements
The Create React App is maintained by Facebook and can works on any platform, for example,
macOS, Windows, Linux, etc. To create a React Project using create-react-app, you need to have
installed the following things in your system.
Let us check the current version of Node and NPM in the system
Run the following command to check the Node version in the command prompt.
Here you will learn how to set up environment for successful React development.
Notice that there are several steps involved but this will help you to speed up progress process later.
We will need NodeJS so if you don't have it installed, check the link from the below.
Step 3 - Select the default components to be installed. Accept the default components and click on the Next button.
Step 4 - In the next screen, click the “Next” button to continue with the installation
prompt window.
Step 7 - Creating the app in the “local user” folder.
Step 8 - In order to install your app, first go to your workspace (desktop or a folder) and run the following command: npx
create-react-app my-app
Step 8 - After the folder is created we need to open it and see the following files.
Step 9 - After the installation is completed, change to the directory where your app was installed and finally run npm start to see
Step 10 - If you see something like this in your browser, you are ready to work with React.
What is JSX in ReactJS ?
JSX is a preprocessor step that adds XML syntax to JavaScript. You can definitely use React without JSX but JSX
makes React a lot more elegant. Just like XML, JSX tags have a tag name, attributes, and children.
Coding JSX
It allows us to write HTML elements in JavaScript and place them in the DOM without
To use JSX is not compulsory, but JSX makes it easier to write React applications.
In this example, JSX allows us to write HTML directly within the JavaScript code. JSX is an extension of the
Expressions in JSX
The expression can be a React property, or variable, or some other valid JavaScript expression. It will execute the expression
import './index.css';
ReactDOM.render(element, document.getElementById('root'));
Output
The class attribute is a much-used attribute in HTML, but meanwhile JSX is extracted as JavaScript, and the class
keyword is a reserved word in JavaScript, you are not permitted to use it in JSX.
JSX resolved this by using className in its place. When JSX is rendered, it interprets className attributes
Example:
import './index.css';
ReactDOM.render(element, document.getElementById('root'));
Output
Hello Wikitechy
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.
DOM stands for "Document Object Model". It denotes the entire UI of the web application as a tree data structure.
Whenever there is a change in the state of application UI, the DOM gets updated and represents that change.
With every change, the DOM gets manipulated and re-rendered to update the application UI, which affects the
Hence, with more UI components and complex structure of the DOM, the DOM updates will be more costly as with
To make the performance of the Real DOM quicker and better, the idea of Virtual DOM shows up. The Virtual DOM
But the difference is, each time with each change , the virtual DOM gets reorganized instead of the real DOM
Like, real DOM , virtual DOM is also denoted as a tree structure. Every element is a node in this tree.
When a new item is added to the application UI, a node is added to the tree also.
If the state of any of these components changes, another virtual DOM tree is created.
The virtual DOM figures the most ideal way or we can say the small procedure on the real DOM to make changes to
Hence, it makes efficient and better performance by reducing the cost and operations of re-rendering the whole real
DOM.
Now that we have the basic understanding of Real and Virtual DOM, let's focus on how React works using the Virtual DOM.
In React, each UI is an different component and each component has its individual state.
React follows the visible pattern and detects the changes of the states.
Whenever a change is made in the state of any component, React updates the virtual DOM tree but does not change the
After updating, react compares the recent version of the virtual DOM with the earlier version.
React knows which objects are altered in the virtual DOM, based on that it only changes those objects in the Real
This process is noted as "diffing". A picture below will clear the concept more.
This process is noted as "diffing". A picture below will clear the concept more.
Here the red circles are the nodes that has been changed. That means, the state of these components is changed. React
computes the difference of the previous and current version of the Virtual DOM tree and the whole parent sub-tree gets
Then the updated tree is batch updated (This means that updates to the real DOM are sent in groups, instead of sending
State is only seen on the inside of component definitions where as Props are defined when components are created by
The main difference between state and props is that props are immutable.
Props are passed to components through HTML attributes. props stands for properties.
React Props
React Props are like function arguments in JavaScript and attributes in HTML.
To send props into a component, use the same syntax as HTML attributes:
Sample Code
import './index.css';
function Wikitechy(props) {
ReactDOM.render(element, document.getElementById('root'));
Output
Components are independent and reusable bits of code. They serve the same purpose as JavaScript functions, but
work in isolation and return HTML.
React component is the building block of a React application. Let us learn how to create a new React component and
the features of React components in this chapter.
A React component represents a small chunk of user interface in a webpage. The primary job of a React component
is to render its user interface and update it whenever its internal state is changed. In addition to rendering the UI, it
manages the events belongs to its user interface. To summarize, React component provides below functionalities .
Initial rendering of the user interface.
Management and handling of events.
Updating the user interface whenever the internal state is changed.
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.
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. unction 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.
Example
Output:
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.
Output:
State in Reactjs ?
What is State in Reactjs ?
You should try to create your state as simple as possible and minimize number of stateful components.
For example, ten components that want data from the state, you should create one container component that will
Calling setState triggers UI updates and is the bread and butter of React's interactivity.
If we want to set an initial state before any interaction occurs we can use the getInitialState method.
setState triggers UI updates and to get the initial state before the setState : getInitialState.getDefaultProps
setState triggers UI updates and to get the initial state before the setState :
getInitialState.getDefaultProps
Reactjs maintained the state – getIntialState, setState, getDefaultProps.
In the above example we are getting the count variable to 5 and accessing it by {this.state.count}
Article tag : react , react native , react js tutorial , create react app , react tutorial , learn react
Example
var MyComponent = React.createClass({
getInitialState: function(){
return {
count: 5
}
},
render: function(){
return (
<h1>{this.state.count}</h1>
)
}
});
Using Props
Below code shows how to create stateful component using EcmaScript2016 syntax.
Article tag : react , react native , react js tutorial , create react app , react tutorial , learn react
App.jsx
import React from 'react';
this.state = {
header: "Header from state...",
"content": "Content from state..."
}
}
render() {
return (
<div>
<h1>{this.state.header}</h1>
<h2>{this.state.content}</h2>
</div>
);
}
}
Output
React Component Life-Cycle
Lifecycle Methods
o Mounting
o Updating
o Unmounting
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.
o 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.
o 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
o 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.
o componentDidMount()
This is invoked immediately after a component gets rendered and placed on the DOM. Now,
you can do any DOM querying operations.
o 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.
o 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.
o 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.
o 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.
o 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.
o 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.
o 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
import React, { Component } from 'react';
When you click on the Click Here Button, you get the updated result which is shown in the below
screen.
LocalStorage in ReactJS:
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');
Example
App.jsx
import React, { useState } from 'react';
<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>
</div>
);
};
export default App;
Output
This will produce the following result.
Lifting State up in ReactJS
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).
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';
handleTextChange(e){
this.props.handleTextChange(e.target.value);
}
render() {
return (
<input value={this.props.text}
onChange={this.handleTextChange} />
);
}
}
export default B;
React Events:
An event is an action that could be triggered as a result of the user action or system generated event. For example, a
mouse click, loading of a web page, pressing a key, window resizes, and other interactions are called events.
React has its own event handling system which is very similar to handling events on DOM elements. The react event
handling system is known as Synthetic Events. The synthetic event is a cross-browser wrapper of the browser's
native event.
Handling events with react have some syntactic differences from handling events on DOM. These are:
React events are named as camelCase instead of lowercase.
With JSX, a function is passed as the event handler instead of a string. For example
Adding Events
React events are written in camelCase syntax:
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:
OUTPUT:
When you execute the above code, you will get the following output.
After entering the name in the textbox, you will get the output as like below screen.
Set State
This method will not replace the state but only add changes to original state
Example:
import React from 'react';
constructor() {
super();
this.state = {
data: []
}
this.setStateHandler = this.setStateHandler.bind(this);
};
setStateHandler() {
myArray.push(item)
this.setState({data: myArray})
};
render() {
return (
<div>
</div>
);
Output:
Force Update
forceUpdateHandler() {
this.forceUpdate();
};
render() {
return (
<div>
<button onClick = {this.forceUpdateHandler}>FORCE UPDATE</button>
<h4>Random number: {Math.random()}</h4>
</div>
);
}
}
export default App;
We are setting random number that will be updated every time the button is clicked.
Output
Output
Composition And Inheritance In React.Js:
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() {
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 {
render() {
return (
<div>
< UserNameForm />
<button>Update</button>
</div>
)
}
}
ReactDOM.render(
(<div>
<CreateUserName />
<UpdateUserName />
</div>), document.getElementById('root')
);