You are on page 1of 21

20MCAE04-Full Stack Web Development REACT

REACT

React Native is a JavaScript framework created by Facebook for writing real mobile
applications especially for iOS and Android. It comes out of React, Facebook’s JavaScript
library used for building user interfaces but it mainly focuses on Mobile Platforms. ReactJS is
a frontend library that runs on a browser with many kinds of the old webserver.

It was created and developed by Jordan Walke, it was deployed first on the Facebook newsfeed
in 2011.

Evolution Of React

React is a JavaScript library used to build the user interface for web applications. React was
initially developed and maintained by the folks at Facebook, which was later used in their
products (WhatsApp & Instagram). Now it is an open source project with an active developer
community. Popular websites like Netflix, Airbnb, Yahoo!Mail, KhanAcademy, Dropbox and
many more use React to build their UI. Modern websites are built using MVC (model view
controller) architecture. React is the ‘V’ in the MVC which stands for view, whereas
the architecture is provided by Redux or Flux. React native is used to develop mobile apps,
the Facebook mobile app is built using React native.

Facebook’s annual F8 Developer conference 2017, saw two promising announcements: React
Fiber and ReactVR. React Fiber is a complete rewrite of the previous release focusing on
incremental rendering and quick responsiveness, React Fiber is backward compatible with all
previous versions. ReactVR is built on top of React Native frameworks, it enables developing
UI with the addition of 3D models to replicate 360-degree environment resulting in fully
immersive VR content.

The following reasons make one use React for building User Interfaces (UI), and they are:

• Easy to learn nature

• Simplicity

• High scalability

• Increase performance

SHOBHA RANI BR, DR. AIT 1


20MCAE04-Full Stack Web Development REACT

FEATURES OF REACT

The features of React JS are as follows:

1. React improves SEO performance

React boost the performance of the SEO to higher levels as a search engine faces the problem
while reading JavaScript of high-loaded applications.

2. React acts as a standard for mobile app development

It provides a transition process as an ideal solution for both mobile and web applications for
building rich user interfaces.

3. React makes the process of writing components easier

Using React along with JSX will make you write components and code efficiently and clearly.

4. React increases efficiency

React boost the efficiency of components by reusing them. This is the reason why it is
considered an ideal feature of React. It is considered the most reusable system component.

5. React ensures stable code

It ensures the stability of the code of an application by making use of downward data flow.

Features In Details

Declarative:

React creates very interactive and dynamic user interface for websites and mobile applications.
Create simple views for each state in your application, and React will efficiently update and
render just the right components when your data changes. Declarative views make your code
more readable and easier to debug.

Virtual DOM:

In React, for every DOM object, there is a corresponding “virtual DOM object.” A virtual
DOM object is a representation of a DOM object, it creates a virtual copy of the original DOM.
It’s a one-way data binding hence manipulating the virtual DOM is quick rather than updating
original DOM because nothing gets drawn onscreen.

SHOBHA RANI BR, DR. AIT 2


20MCAE04-Full Stack Web Development REACT

Event handling:

React creates its own event system which is fully compatible with W3C object model. All
browser’ native events are wrapped by instances of Synthetic Event. It provides a cross-
browser interface to a native event. That means you do not need to worry about incompatible
event names and fields. Besides, React event system is implemented through event delegation
and also has a pool of event objects to reduce memory overhead.

JSX:
JSX can best be thought of as a markup syntax that very closely resembles HTML.It is more
or less like the combination of Javascript + XML. JSX makes writing React components, the
building blocks of React UI, easier by making the syntax developers use for generating these
strings of HTML almost identical to the HTML they will inject into the web page.JSX is one
of best ReactJS features. Web developers will always go for an easy way out, which is why
this is a great choice for many.

Performance:
React uses one-way data binding with an application architecture called Flux controls.ReactJS
helps us update the View for the user and, with Flux, can control the application workflow.
Introducing virtual DOM adds advantages where it compares the new data with original DOM
and automatically updates the view.

React Native:

React Native is a custom renderer for React, just like React DOM on The Web. React Native
uses native components instead of web components like React as building blocks. To begin
with React Native, you need to know the basic React concepts, like JSX, components, state,
and props. If you know React, you still need to learn stuff specific to React Native, like the
native components. React Native also gives access to the features these platforms offer, apart
from transforming React code to work on iOS and Android.

Component-Based:
In React everything is component the web page divided into small components to create a view
(or UIs). Every part of applications visuals would be wrapped inside a self-contained module
known as a component. Since component logic is written in JavaScript instead of templates,
you can easily pass rich data through your app and keep the state out of the DOM. Components
in ReactJS use to define the visuals and interactions in applications.

SHOBHA RANI BR, DR. AIT 3


20MCAE04-Full Stack Web Development REACT

ADVANTAGES OF REACTJS

• Intuitive
ReactJS is extremely intuitive to work with and provides interactivity to the layout of
any UI. Plus, it enables fast and quality assured application development that in turn
saves tome for both - clients and developers.

• Declarative
ReactJS enables significant data changes that result in automatic alteration in the
selected parts of user interfaces. Owing to this progressive functionality, there is no
additional function that you need to perform to update your user interface.

• Provides Reusable Components

ReactJS provides reusable components that developers have the authority to reuse and
create a new application. Reusability is exactly like a remedy for developers. This
platform gives the developers the authority to reuse the components build for some
other application having the same functionality. Thereby, reducing the development
effort and ensuring a flawless performance.

• JavaScript library

A strong blend of JavaScript and HTML syntax is always used, which automatically
simplifies the entire process of writing code for the planned project. The JS library
consists several functions including one that converts the HTML components into
required functions and transforms the entire project so that it is easy to understand.

• Components Support

ReactJS is a perfect combination of JavaScript and HTML tags. The usage of the HTML
tags and JS codes, make it easy to deal with a vast set of data containing the document
object model. During this time, ReactJS works as a mediator which represents the DOM
and assists to decide which component needs changes to get the exact results.

• SEO-friendly

React JS was introduced after immense research and improvements by Facebook.


Naturally, it stands out from the crowd and allows developers to build amazing, SEO-
friendly user interfaces across browsers and engines.

SHOBHA RANI BR, DR. AIT 4


20MCAE04-Full Stack Web Development REACT

• Proficient Data Binding

ReactJS trails one-way data binding. This means that absolutely anyone can track all the
changes made to any particular segment of the data. This is a symbol of its simplicity.

Difference between Virtual and Real DOM

Virtual Document Object Model (DOM)

The Virtual DOM is React's lightweight version of the Real DOM. Real DOM manipulation is
substantially slower than virtual DOM manipulation. When an object's state changes, Virtual
DOM updates only that object in the real DOM rather than all of them.

Browser's DOM

DOM stands for "Document Object Model". It represents the entire UI of the web
application as a tree data structure. In simpler terms, it is a structural representation of the
HTML elements of the web application.

SHOBHA RANI BR, DR. AIT 5


20MCAE04-Full Stack Web Development REACT

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 performance and makes it slower.

Hence, with more UI components and complex structure of the DOM, the DOM updates will
be more costly as with every change it needs to be re-rendered.

React's Virtual DOM

To make the performance of the Real DOM better and faster, the concept of Virtual DOM
arrives. The Virtual DOM is nothing but the virtual representation of the DOM.

But the key difference is, every time with every change , the virtual DOM gets updated instead
of the real DOM.

Like, real DOM , virtual DOM is also represented as a tree structure. Each element is a node in
this tree. When a new item is added to the application UI, a node is added to the tree as well.
If the state of any of these elements changes, a new virtual DOM tree is created. The virtual
DOM computes the best possible way or we can say the minimal operations on the real DOM
to make changes to the real DOM. Thus, it makes efficient and better performance by reducing
the cost and operations of re-rendering the whole real DOM.

SHOBHA RANI BR, DR. AIT 6


20MCAE04-Full Stack Web Development REACT

Working of React using the Virtual DOM.

In React, each UI is an individual component and each component has it's own state.

React follows the observable pattern and observes 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 real DOM tree
After updating, React then compares the current version of the virtual DOM with
the previous version.
React knows which objects are changed in the virtual DOM, based on that it only changes
those objects in the Real DOM, making minimum manipulating operations.
This process is noted as "diffing". A picture below will clear the concept more.

In this image, the red circles are the nodes that has been changed. That means, the state of
these components are changed. React computes the difference of the previous and current
version of the Virtual DOM tree and the whole parent sub-tree gets re-rendered to show the
changed UI. Then the updated tree is batch updated (This means that updates to the real DOM

SHOBHA RANI BR, DR. AIT 7


20MCAE04-Full Stack Web Development REACT

are sent in batches, instead of sending updates for every single change in state.) to the Real
DOM.

Interaction of Virtual DOM and React DOM

When the state of an object changes in a React application, VDOM gets updated. It then
compares its previous state and then updates only those objects in the real DOM instead of
updating all of the objects. This makes things move fast, especially when compared to other
front-end technologies that have to update each object even if only a single object changes in
the web application.

ES6 stands for ECMAScript 6.

ECMAScript was created to standardize JavaScript, and ES6 is the 6th version of ECMAScript,
it was published in 2015, and is also known as ECMAScript 2015.

Set up React Environment

You can set up a React environment with create-react-app, which comes with boilerplate code
with everything set up to build your project. It creates a live development server
at localhost:3000 where 3000 is the port number, it uses webpack to automatically compile
React, ES6 and JSX.

To set up create-react-app, ensure you have Node and npm installed on your computer. Note
that npm is install automatically when you install Node

You can install create-react-app by running the following command in your terminal.

>npx create-react-app hello world

OR

>npm install create-react-app -g

>create-react-app hello world

The hello world represents the name of your project. You can call it anything you want.

The create-react-app will set up react environment with everything you need. When it is
completed, run the react application with the following commands.

>cd hello world


>npm start

SHOBHA RANI BR, DR. AIT 8


20MCAE04-Full Stack Web Development REACT

A new browser window will pop up with your newly created React app hosted on
localhost:3000. If it does not, go to your browser and type localhost:3000.

Your react app will run on that portal, just as seen above.

The react environment from your create-react-app includes these files/folder

• node_modules — contains all the node dependencies.

• public — public files that are served.

• src — source code of your react app.

• gitignore — records which files git should ignore.

• package.json — contains various metadata relevant to the project.

• package-lock.json — contains an exact version dependency tree.

Modify the React Application

Remove unnecessary imports from the app.js in the src folder. Change the HTML content and
save the file.

SHOBHA RANI BR, DR. AIT 9


20MCAE04-Full Stack Web Development REACT

“Welcome to reactjs” displayed in your browser.

Flow of control upon npm start

➢ index.html is served in browser


o It contains the root DOM node <div id=“root”>
➢ Control moves to index.js
➢ Here ReactDOM renders App component on to the root DOM node
➢ The App Component contains html that is displayed on the browser

Difference between App.js and index.js

index.js is the traditional and actual entry point for all node apps. Here in React it just has code
of what to render and where to render.

App.js on the other hand has the root component of the react app because every view and
component are handled with hierarchy in React, where <App /> is the top most component in
the hierarchy. This gives you the feel that you maintain hierarchy in your code starting
from App.js.

SHOBHA RANI BR, DR. AIT 10


20MCAE04-Full Stack Web Development REACT

Components

Components are the building blocks that comprise a React application representing a part of
the user interface. 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. React renders multiple components
simultaneously. Components can be either stateful or stateless.

A component can be either a class-based or a function-based.

2 Types of Components

➢ Function based Component


➢ Class based Component

Function-based component

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. Also, these types of components are also referred as stateless
or representational components because they are best used to only display UI. They are easy
to read, debug, and test.

Syntax:

import React from 'react';


const App = () => {
return(
/* <div>JSX</div> */
)
}

SHOBHA RANI BR, DR. AIT 11


20MCAE04-Full Stack Web Development REACT

exports default App;

Example:

const college = () => {


return (
<div>
<p>Dr. Ambedkar Institute of Technology!</p>
</div>
)
}
export default college;

In the code above, it is a very simple component that consists of a constant variable college that
is assigned to an arrow function which returns JSX. Functional components do not need to be
arrow functions. They can be declared with regular JavaScript functions. We can also pass
in props to the function and use them to render data in the JSX code.

Class-based Component

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. We can
pass data from one class to other class components. Can create a class by defining a class that
extends Component and has a render function.

A class-based component is also known as a stateful component or container component and


it is created as follows:

import React from ‘react’


class App extends React.Component{
render(){
return(
/* <div>JSX</div> */
)
}
}
exports default App;

Example:

class App extends React.Component{


render(){
return(

SHOBHA RANI BR, DR. AIT 12


20MCAE04-Full Stack Web Development REACT

<p>Dr. Ambedkar Institute of Technology!</p>


);
}
}
export default App;

Class component syntax differs from functional component syntax. Class components
use extends React.Component after declaring the class college and requires a render() method
to return JSX code.

Props in React

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. React Props are like function arguments in
JavaScript and attributes in HTML. They provide a channel through which components
communicate.

To send props into a component, use the same syntax as HTML attributes:

Props can be used to pass any kind of data such as:

➢ String
➢ Array
➢ Integer
➢ Boolean
➢ Objects or,
➢ Functions

Example-1:

import React from 'react';


class App extends React.Component {
render() {
return (
<div>

<h3>Welcome to {this.props.name}</h3>
<p>Full stack Web Development</p>
</div>
);
}
}
App.defaultProps = {
name: "Full stack"
}
export default App;

SHOBHA RANI BR, DR. AIT 13


20MCAE04-Full Stack Web Development REACT

In the above example, 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.

Example-2:

We can add props in the component in the same way that we add attributes in our HTML.

App.js

import React from 'react';


import Branch from './components/Branch.js';
class App extends React.Component {
render() {
return (
<div>
<Branch name = "Computer Science" />
<Branch name = "Information Science" />
</div>
);
}
}
export default App;

In the above file, we have used a name attribute with the desired dynamic value after rendering
the data. Now, the most important point here is to pass props to the child component.

Passing props to Branch.js

const Branch = (props) => {


return < h1 > {props.name} </ h1>
}
export default Branch;

It is a plain JavaScript object with key-value pairs. We can access the value as key of
“name” using (.) dot notation like this >>> “props.name“
In the final step, we have used interpolation to use the props and we enclose it in curly brackets
because it is a JSX expression.

SHOBHA RANI BR, DR. AIT 14


20MCAE04-Full Stack Web Development REACT

React states

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.
The state is a built-in React object that is used to contain data or information about the
component. A component’s state can change over time; whenever it changes, the component
re-renders. The change in state can happen as a response to user action or system-generated
events and these changes determine the behavior of the component and how it will render.
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.

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.

Constructor
The constructor is a method used to initialize an object's state in a class. It automatically called
during the creation of an object in a class.
The concept of a constructor is the same in React. The constructor in a React component is
called before the component is mounted. When you implement the constructor for a React
component, you need to call super(props) method before any other statement. If you do not
call super(props) method, this.props will be undefined in the constructor and can lead to bugs.
Syntax
Constructor(props){
super(props);
}

SHOBHA RANI BR, DR. AIT 15


20MCAE04-Full Stack Web Development REACT

In React, constructors are mainly used for two purposes:


• It used for initializing the local state of the component by assigning an object to this.state.
• It used for binding event handler methods that occur in your component.

setState() method cannot be directly called in the constructor(). If the component needs to use
local state, you need directly to use 'this.state' to assign the initial state in the constructor. The
constructor only uses this.state to assign initial state, and all other methods need to use
set.state() method.

Example:
import React from 'react';

class Subject extends React.Component {


constructor(props) {
super(props);
this.state = {
dep: "MCA",
sub: "Data Science"
};
}
changeIDE = () => {
this.setState({sub: "Full Stack"});
}
render() {
return (
<div>
<h2>Department is {this.state.dep}</h2>
<p>
My IDE is {this.state.sub}
</p>
<button type="button" onClick={this.changeIDE}>Change IDE</button>
</div>
);
}
}
export default Subject;

Difference between props and state


State
The state is an updatable structure that is used to contain data or information about the
component and can change over time. The change in state can happen as a response to user
action or system event. It is the heart of the react component which determines the behavior of
the component and how it will render. A state must be kept as simple as possible. It represents

SHOBHA RANI BR, DR. AIT 16


20MCAE04-Full Stack Web Development REACT

the component's local state or information. It can only be accessed or modified inside the
component or by the component directly.
Props
Props 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 allows passing data from one component to other
components. It is similar to function arguments and can be passed to the component the same
way as arguments passed in a function. Props are immutable so we cannot modify the props
from inside the component.
State Vs. Props

PROPS STATE

1. Props are read-only. State changes can be asynchronous.

2. Props are immutable. State is mutable.

3. Props allow you to pass data from one State holds information about the
component to other components as an components.
argument.

4. Props can be accessed by the child State cannot be accessed by child


component. components.

5. Props are used to communicate between States can be used for rendering dynamic
components. changes with the component.

6. Stateless component can have Props. Stateless components cannot have State.

7. Props make components reusable. State cannot make components reusable.

SHOBHA RANI BR, DR. AIT 17


20MCAE04-Full Stack Web Development REACT

Life-Cycle of Components

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

SHOBHA RANI BR, DR. AIT 18


20MCAE04-Full Stack Web Development REACT

single root HTML node element. If you don't want to render anything, you can return
a null or false value.

Mounting:
Mounting is the process of creating an element and inserting it in a DOM tree. This
phase has two functions or methods that can hook up
with componentWillMount() and componentDidMount().

Here we can see, Header, Content, Footer are components that will store in Virtual DOM
Memory before the Mounting phase. When Mounting will invoke, all the elements and content
will render to the user interface in the browser.
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 component’s 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.

SHOBHA RANI BR, DR. AIT 19


20MCAE04-Full Stack Web Development REACT

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

Updating is the process of changing state or props of component and update changes to nodes
already in the DOM.

SHOBHA RANI BR, DR. AIT 20


20MCAE04-Full Stack Web Development REACT

During this phase, a React component is already inserted into the DOM. Thus these methods
are not called for the first render().
The componentWillUpdate() method is called immediately before rendering, when new props
or state are being received.
The componentDidUpdate() method is called immediately after React updates the DOM.
Visual representation of the phases: Updating

Here we can see, React found some update in content then it will first change in Virtual DOM
then Reflect the change in Browser User Interface.
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.

Unmounting:
unmounting is the process of removing components from the DOM. It is called immediately
before the component is unmounted from the DOM.

SHOBHA RANI BR, DR. AIT 21

You might also like