WT MOD - 3 (ELECTIVE MBCET NOTES - CT) 23

PerfectOK1 0 views 101 slides Oct 24, 2025
Slide 1
Slide 1 of 101
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49
Slide 50
50
Slide 51
51
Slide 52
52
Slide 53
53
Slide 54
54
Slide 55
55
Slide 56
56
Slide 57
57
Slide 58
58
Slide 59
59
Slide 60
60
Slide 61
61
Slide 62
62
Slide 63
63
Slide 64
64
Slide 65
65
Slide 66
66
Slide 67
67
Slide 68
68
Slide 69
69
Slide 70
70
Slide 71
71
Slide 72
72
Slide 73
73
Slide 74
74
Slide 75
75
Slide 76
76
Slide 77
77
Slide 78
78
Slide 79
79
Slide 80
80
Slide 81
81
Slide 82
82
Slide 83
83
Slide 84
84
Slide 85
85
Slide 86
86
Slide 87
87
Slide 88
88
Slide 89
89
Slide 90
90
Slide 91
91
Slide 92
92
Slide 93
93
Slide 94
94
Slide 95
95
Slide 96
96
Slide 97
97
Slide 98
98
Slide 99
99
Slide 100
100
Slide 101
101

About This Presentation

Web Technology MBCET Module 3 notes


Slide Content

MODULE - 3
React and Single Page Application (SPA) Development SPA vs MPA Architecture,
React JSX, Components, Props, State, Lifecycle Methods, React Hooks (useState,
useEffect), Event Handling, Conditional Rendering, React Router, Context API,
Overview of AngularJS and Vue.js
BINDHYA PS , MBCET 1

BINDHYA PS , MBCET 2

Single Page Application
•A Single Page Application (SPA) is a type of web application or website that interacts with the user by
dynamically rewriting the current page, rather than loading entire new pages from the server.
•When a user interacts with an SPA, only the necessary data is fetched and updated, eliminating the need
for page reloads.
Key Characteristics of SPAs
•No Page Reloads: SPAs load once, and after that, only specific content changes without full page reloads.
•Asynchronous Data Fetching: SPAs fetch data in the background using APIs (e.g., RESTful or GraphQL APIs) and
display it without refreshing the page.
•Dynamic Content: SPAs update content based on user interactions, such as clicks, form submissions, or navigation
within the app, all while maintaining the same page structure
Example: Youtube, Gmail, facebook, Twitter, Trello 3

Single Page Application
•A Single Page Application (SPA) is a type of web application that loads and updates content dynamically without
refreshing the entire page.
4

SPA vs MPA (Multi Page Application):
(Search Engine
Optimization)
5

Timeline of front-end JavaScript frameworks
BINDHYA PS , MBCET 6

Common tasks in front-end development
BINDHYA PS , MBCET 7

What is React?
•React is a JavaScript framework
•Used for front end web development
•Think of jQuery, but more structured
•Created and used by Facebook
•Famous for implementing a virtual dom
1. JavaScript and HTML in the same file (JSX)
2. Embrace functional programming
3. Components everywhere
BINDHYA PS , MBCET 8

What is React JS?
•React JS is an open-source JavaScript library for building rich user
interfaces.
•React is a JavaScript library that allows for the creation of complex and
dynamic user interfaces – making it an ideal choice for single page
applications.
•React provides developers with the tools and technologies they need to
develop fast and efficient SPAs quickly.

BINDHYA PS , MBCET 9

Building Your SPA Application
Prerequisites/Downloads
•Node.js: The latest version of Node.js on your machine.
–npm → Node Package Manager , npx → Node Package eXecute[npm-v; npx –v]
•React Library: The latest version of React on your machine.
•A Code Editor: Any IDE that supports React.(Visual Studio)
Steps
•create-react-appnpx create-react-app myapp
•Navigate to myapp foldercd myapp
•Install react router dom packagenpm install react-router-dom
•Run the application npm start[ctrl+c to stop app]

10

Install VS Code extension
Extension
•ES7+ React/Redux/React-Native snippets
•Prettier – Code formatter
•Simple React Snippets

How to install a VS Code extension
•Click the Extensions icon on the left sidebar (or press Ctrl+Shift+X).
•Search for the extension name (e.g., Prettier).
•Click Install.
BINDHYA PS , MBCET 11

Building Your SPA Application
•Routing means controlling which component (page) is shown
based on the URL path.
•index.html Body section<div> where to render …
•Src folder index.js App.js – application starts
•Uses jsx code.
–JavaScript XML- It’s a syntax extension for JavaScript that lets you write
HTML-like code inside JavaScript when working with React.

App.js component
.\ Same folder
BINDHYA PS , MBCET 12

new React app

13

Introducing JSX
•JSX: Putting markup into JavaScript
•logic and markup in same place
Html code
<h1>Varieties of Lotus</h1>
<img src="https://abc.jpg" alt=“flower"
class="photo">
<ul>
<li>Pink Lotus
<li>Wild lotus
<li>Cherry Lotus
</ul>
To add in Component
export default function TodoList() {
return (
// ???
)
}
BINDHYA PS , MBCET 14

The Rules of JSX
1. Return a single root element
•To return multiple elements from a component, wrap them with a single parent tag.
<div>
<h1>Varieties of Lotus</h1>
<img src="https://abc.jpg" alt=“flower"
className="photo">
<ul>
<li>PinkLotus
<li>Wild lotus
<li>Cherry Lotus
</ul>
</div>
If you don’t want to add an extra <div> to
your markup, you can write <> and </>
instead:
BINDHYA PS , MBCET 15

The Rules of JSX
•This empty tag is called a Fragment.
<> and </> or
<React.Fragment> and </React.Fragment>
export default function TodoList()
{
return (
<>
<h1>Varieties of Lotus</h1>
<img src="https://abc.jpg" alt=“flower"
className="photo">
<ul>
<li>Pink Lotus
<li>Wild lotus
<li>Cherry Lotus
</ul>
</>
);
}
Build a React component to render multiple
elements without introducing extra nodes in the
DOM. – React. Fragment
16

JavaScript XML
Ex 1:
<React.Fragment>
<p> Title 1 </p>
<p> Title 2 </p>
</React.Fragment>


{} javascript element
function App() {
return (
<div>
<h1>Title</h1>
<p>Description</p>
</div>
);
}
In React, a component’s return can only have one root element.
BINDHYA PS , MBCET 17

The Rules of JSX
export default function Bio()
{
return (
<div class="intro">
<h1>Welcome!</h1>
</div>
<p class="summary">
You can find my thoughts
here.
<br> <br>
<b>And pictures</b>
of scientists!
</p>
);
}
export default function Bio()
{
return (
<div>
<div className="intro">
<h1>Welcome!</h1>
</div>
<p className="summary">
You can find my thoughts here.
<br/> <br/>
<b>And pictures</b>
of scientists!
</p>
</div>
);
}
18

Passing strings with quotes

•To pass a string attribute to JSX, put it in single or double quotes:
export default function TodoList() {
const name = "Nandan";
return <h1>{name}'s To Do List</h1>;
}

{} specifies javascript
<p> { “Welcome”} </p>
<p> {“1+2”} </p>
BINDHYA PS , MBCET 19

Functional programming
20

Functional programming
Variables are immutable
Variables being "immutable" means
that once a variable is assigned a
value, that value cannot be changed
through that variable.
BINDHYA PS , MBCET 21

Style
BINDHYA PS , MBCET 22

function formatDate() {
const today = new Date();
const days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
const months = ["January", "February", "March", "April", "May", "June", "July", "August", "September",
"October", "November", "December" ];
const dayName = days[today.getDay()];
const monthName = months[today.getMonth()];
const dayNumber = today.getDate();
const year = today.getFullYear();
return (
<div>
<h2>Day: {dayName}</h2>
<h2>Month: {monthName}</h2>
<h2>Date: {dayNumber}</h2>
<h2>Year: {year}</h2>
</div>
);
}
BINDHYA PS , MBCET 23

Develop a personalized greeting using JSX

Ex 4:
function App() {
var name = "Gayathri";
return (
<div>
<p>Welcome {name}</p>
</div>
);
}

Ex 5:
function Greet(name) {
return <h3>{name}</h3>;
}
function App() {
return (
<div>
{Greet("Tintu")} or <Greet name="Tintu" />
{Greet("Mia")} or <Greet name="Mia" />
</div>
);
}
BINDHYA PS , MBCET 24

JavaScript XML
Ex 6:
function App(){
const age = parseInt(prompt("Enter your age:"),10);
return(
<div>
<p>You are {age>=18?”eligible”:”not eligible”}</p>
</div>
);
}
BINDHYA PS , MBCET 25

Importing and Exporting Components
–The magic of components lies in their reusability

function Profile()
{
return (
<img src="lotus.jpg" alt="beautiful lotus flower" />
);
}
export default function Gallery()
{
return (
<section>
<h1>Amazing flowers</h1>
<Profile />
<Profile />
<Profile />
</section>
); }
<Profile /> looks like an HTML tag,
but it’s actually a function call to React component
Gallery.js
Export the component
Gallery()
26

Importing and Exporting Components
App.js

import Gallery from './Gallery.js';

export default function App()
{
return (
<Gallery />
);
}
Two component files :
Gallery.js:
•Defines the Profile component which is only used within the
same file and is not exported.
•Exports the Gallery component as a default export.
App.js:
•Imports Gallery as a default import from Gallery.js.
•Exports the root App component as a default export.
A file can only have one default export, but it can have numerous named exports!
27

Importing and Exporting Components
App.js

import Gallery from './Gallery.js';
Import {Profile} from './Gallery.js';

export default function App()
{
return (
<Profile />
);
}
Gallery.js
export function Profile()
{
return (
<img src="lotus.jpg" alt="beautiful lotus flower" />
);
}
export default function Gallery()
{
return (
<section>
<h1>Amazing flowers</h1>
<Profile />
<Profile />
<Profile />
</section>
); }
•JavaScript module to export and import
using function component
28

Import/Export
Home.jsIndex.js
29

Import/Export
Contact.js Index.js
30

Import/Export in Javascript
// file: abc.js
export function add(a, b) {
return a + b;
}
export const PI = 3.1416;

// file: main.js
import { add, PI } from './abc.js';
console.log(add(5, 3)); // 8
console.log(PI); // 3.1416
31

Import/Export in Javascript
1.Default Import
import Something from 'file‘ . Function name is arbitrary

2.Named Import
import {Profile} from ‘Gallery.js‘ Must match exported names

import {Profile as Pro } from ' Gallery.js‘ directly rename import
BINDHYA PS , MBCET 32

Components - In React, everything is a component
BINDHYA PS , MBCET 33

Components
1.Functional components take only props as an
argument and return react elements.
2.Functional components are state less
components and no life cycle methods.
3.Class components extends by react base class
name is Component. It help to set the state
and implement the life cycle methods.
4.Class components we have render method
which is used for return the react elements.
BINDHYA PS , MBCET 34

Function React component
35

Components can refer to other components in their output.
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
function App() {
return (
<div>
<Welcome name="Sara" />
<Welcome name=“Kanhar" />
<Welcome name=“Diya" />
</div>
);
}
Props are Read-Only
•Functions are called “pure” because they do not
attempt to change their inputs, and always return the
same result for the same inputs.
function sum(a, b) {
return a + b;
}
BINDHYA PS , MBCET 36

Fucntional component
•It is simply a javascript function. These function may or may not receive data as
parameters.


A button, a form, a dialog, a screen: in React apps, all those are commonly
expressed as components.
BINDHYA PS , MBCET 37

Properties
import React from "react";
function Contact(props) {
return (
<div>
<p> {props.id} </p>
<h1>{props.name} CONTACT INFORMATION</h1>
<label> Email ID:</label>
<input type="text" />
<br></br>
<label>Message</label>
<textarea></textarea>
<button>SEND</button>
</div>
);
}
export default Contact;


Home.js
import logo from './logo.svg';
import Contact from './Home.js';
import './App.css';

function App() {
return (
<div>
<Contact id={1} name="TEACHER"/>
<div>
<p>Thankyou.Have a nice day!</p>
</div>
<Contact name="STUDENT"/>;
</div>
);
}

App.js
BINDHYA PS , MBCET 38

Properties
To pass a objectTo pass an array
Home.js
<Contact info ={{name:"manu" age=25 }}
App.js
<div>
<p> {props.info.name} </p>
<p> {props.info.age} </p>

Home.js
App.js
<Contact info ={[name:"manu" age=25 ]}
<div>
<p> {props.info[0]} </p>
<p> {props.info[1]} </p>

BINDHYA PS , MBCET 39

State
•State vs. Props:
–State is a private, mutable object controlled by a component, while props are
immutable and set by the parent component.
•State allows React components to change their output over time in response to user
actions.
•State can be used in Class Components and implemented in Functional Components
using React hooks like useState.
•State is generally updated by event handlers, whereas props remain unchanged once set.
BINDHYA PS , MBCET 40

Props vs State in React
Props State
Used to transfer data from a parent component to a
child.
Used to manage data inside a component itself.
Immutable (cannot be changed within the
component).
Mutable (can be updated using setState or useState).
Can be used with both functional and class
components.
Used mainly within the component where it is defined
(class components with this.state or functional
components with hooks).
Read-only. Read & Write (can be updated).
Passed down from parent and are read-only in the
child.
Accessible only within the component where it’s
defined.
Used to customize behavior or appearance of a
component.
Used to track information that changes over time (e.g.,
user input, counters, API responses).
BINDHYA PS , MBCET 41

Class Component
•Stateful component
•A class component that inherits from React.Component.
•This inheritance provides access to React's core functionalities,
including lifecycle methods and state management
BINDHYA PS , MBCET 42

Class Component
•Before React 16.8 introduced hooks, class components were the main way to
manage state and life cycle methods in React.
•A class component is a javascript class that
•Extends React.Component
•Has a render() method
•Can have its own state and life cycle methods
import React,{component} from 'react';
class MyComponent extends Component {
// Component logic
}
BINDHYA PS , MBCET 43

Class Component
import React ,{component} from 'react';
class Car extends Component {
render() {
return <h1>Hello I AM A CAR!</h1>;
}
}
export default Car;
render() Method: Every class component must include a render() method.

React application has a component called Car, which returns a <h1> element.
44
The render() method returns JSX (JavaScript
XML) that describes the visual output of the
component, including elements, other
components, and data.

Props
class Greeting extends Component {
render() {
return <h1>Hello, {this.props.name}!</h1>;
}
}

<Greeting name="Taylor" />
Whether you declare a component as a function or a class, it must never modify its
own props.
BINDHYA PS , MBCET 45

Component Constructor
•If there is a constructor() function in your component, this
function will be called when the component gets initiated.
•The constructor function is where you initiate the component's
properties.
•In React, component properties should be kept in an object
called state.
•The constructor function of the parent component is inherited by
including the super() statement, which executes the parent
component's constructor function, and component has access to
all the functions of the parent component
class Car extends Component {
constructor(props) {
super(props);
this.state = {color: "red"};
}
render() {
return (<h2>I am a {this.state.color}
Car!</h2>);
}
}
BINDHYA PS , MBCET 46
Class name
begin with
capital letters

Class Component
State Management:
•Class components can manage their own internal state using the this.state object.
•The state is mutable and is used to store data that changes over time and affects the component's rendering.
•State is typically initialized in the constructor and updated using this.setState()
this.state = {
count: 0;
};
Event Handlers:
•Event handlers are typically methods in the class.
•They are used to handle user interactions like clicks, form submissions, etc.
•These methods often use this.setState() to update the component's state.
increment = () => {
this.setState({ count: this.state.count + 1 });
};
BINDHYA PS , MBCET 47

State Management
import React, {Component} from ‘react’;
class Mycomponent extends Component {
constructor(props) {
super(props);
this.state = { // initializing state as object
msg:”Hello, Class component”
};
}
}
changeMessage = () => {
this.setState({ msg: “Message Updated});
};
render() { returns output
return (
<div>
<h2>{this.state.msg}</h2>
<button onClick={this.changeMessage}>
Change Message
</button>
</div>
);
}
}

export default Mycomponent;
BINDHYA PS , MBCET 48

State Management
import React from ‘react’;
class Counter extends React.Component {
state = { count: 0 }; // initializing state object
}
}
increment = () => {
this.setState({ count: this.state.count + 1 });
};
reset = () => {
this.setState({ count: 0 });
};
render() { returns output
return (
<div>
<h2>Current count: {this.state.count}</h2>
<button onClick={this.increment}>
Increment
</button>
<button onClick={this.reset}>
Reset
</button>
</div>
);
}
}

export default Counter;
BINDHYA PS , MBCET 49

Props
App.js
import React, { Component } from "react";
import './App.css';
import First from "./component/first";

class App extends Component {
state = {
mystringone:"Debug",
};
handleChange=()=>{
this.setState({mystringone:"Artificial Intelligence"
})
}
BINDHYA PS , MBCET 50
render() {
return (
<div>
<h1>Welcome</h1>
<button onClick={this.handleChange}>Change Text
</button>
<First pass={this.state.mystringone}/>
<First/>
</div>
);
}
}
export default App;

Props
class Greeting extends Component {
render() {
return <h1>Hello, {this.props.name}!</h1>;
}
}

<Greeting name="Taylor" />
BINDHYA PS , MBCET 51

React LifeCycle
•Mounting: Initializes, renders, and
mounts the component
(componentDidMount()).
•Updating: Handles state/prop changes,
re-renders, and updates
(componentDidUpdate()).
•Unmounting: Cleans up before removal
(componentWillUnmount()).
BINDHYA PS , MBCET 52

React LifeCycle
BINDHYA PS , MBCET 53

•React lifecycle methods are special methods in class components that are invoked at different stages of a
component's existence.
•These methods allow developers to execute code at specific points in a component's lifecycle, such as when it
is created, updated, or removed from the DOM.
•While these lifecycle methods are specific to class components, functional components in React achieve
similar functionality using Hooks

There are three main phases in a React component's lifecycle:
•Mounting: This phase occurs when a component is being created and inserted into the DOM for the first time.
•Updating: This phase occurs when a component is re-rendered due to changes in its props or state.
•Unmounting: This phase occurs when a component is being removed from the DOM.

Mounting
BINDHYA PS , MBCET 54
Mounting means putting elements into the DOM.

React has four built-in methods that gets called, in this order, when mounting a component:

•constructor()
•getDerivedStateFromProps()
•render()
•componentDidMount()

The render() method is required and will always be called, the others are optional and will be
called if you define them.

The constructor() method is called before anything else, when the component is initiated, and it
sets up the initial state. The constructor() method is called with the props, as arguments, by calling
the super(props) will initiate the parent's constructor method and allows the component to inherit
methods from its parent (React.Component).

constructor()
BINDHYA PS , MBCET 55
constructor(props) {
super(props); // Always call super(props) before using this.props
this.state = {
count: 0, // Initial state
};
console.log("Constructor called");
}
constructor() method to initialize state and bind methods.
Executed before the component is mounted.

•constructor() and render()
BINDHYA PS , MBCET 56
class Header extends React.Component {
constructor(props) {
super(props);
this.state = {favoritecolor: "red"};
}
render() {
return (
<h1>My Favorite Color is {this.state.favoritecolor}</h1>
);
}
}

ReactDOM.render(<Header />, document.getElementById('root'));

getDerivedStateFromProps()
BINDHYA PS , MBCET 57
Used for updating the state based on props. Executed before every render.
static getDerivedStateFromProps(props, state) {
if (props.value !== state.value) {
return { value: props.value }; // Update state based on new props
}
return null; // No changes to state
}

•getDerivedStateFromProps()
BINDHYA PS , MBCET 58
class Header extends React.Component {
constructor(props) {
super(props);
this.state = {favoritecolor: "red"};
}
static getDerivedStateFromProps(props, state) {
return {favoritecolor: props.favcol };
}
render() {
return (
<h1>My Favorite Color is {this.state.favoritecolor}</h1>
); }
}

createRoot(document.getElementById('root')).render(
<Header favcol="yellow" />
);
The example starts with the favorite
color being "red", but the
getDerivedStateFromProps() method
updates the favorite color based on the
favcol attribute.

This is called when a component gets updated.

componentDidMount()
BINDHYA PS , MBCET 59
componentDidMount() {
console.log("Component has been mounted");
fetch("https://api.example.com/data")// Fetch data from an API
.then(response => response.json())
.then(data => this.setState({ data }));
}
This function is invoked right after the component is mounted on the DOM,
i.e. this function gets invoked once after the render() function is executed for the first time.

•componentDidMount()
BINDHYA PS , MBCET 60
class Header extends React.Component {
constructor(props) {
super(props);
this.state = {favoritecolor: "red"};
}
componentDidMount() {
setTimeout(() => {
this.setState({favoritecolor: "yellow"})
}, 1000)
}
render() {
return (
<h1>My Favorite Color is {this.state.favoritecolor}</h1>
);
}
}
•This is where you run statements that
requires that the component is already
placed in the DOM.
•At first favorite color is red, but after a
second, and it is yellow instead:

Updating
BINDHYA PS , MBCET 61
The next phase in the lifecycle is when a component is updated.

A component is updated whenever there is a change in the component's state or props.

React has five built-in methods that gets called, in this order, when a component is updated:

• getDerivedStateFromProps()
• shouldComponentUpdate()
• render()
• getSnapshotBeforeUpdate()
• componentDidUpdate()

The render() method is required and will always be called, the others are optional and will be
called if you define them.

getDerivedStateFromProps()
BINDHYA PS , MBCET 62
getDerivedStateFromProps(props, state) is a static method that is called just before the
render() method in both the mounting and updating phase in React.
It takes updated props and the current state as arguments.
static getDerivedStateFromProps(props, state) {
if (props.name !== state.name) {
return { value: props.name }; // Update state based on new props
}
return null; // No changes to state
}

•shouldComponentUpdate() determines whether a component should re-render.
•It compares the current and next props/states and returns true if the component
should update or false if it should not.
BINDHYA PS , MBCET 63
shouldComponentUpdate()
shouldComponentUpdate(nextProps, nextState)
It returns true or false, if false, then render(), componentWillUpdate(), and
componentDidUpdate() method does not get invoked.

•shouldComponentUpdate()
BINDHYA PS , MBCET 64
•This method return a Boolean value that specifies whether React should continue with the rendering or not.
•The default value is true.
import { createRoot } from 'react-dom/client'
import React from 'react';

class Header extends React.Component {
constructor(props) {
super(props);
this.state = {favoritecolor: "red"};
}
shouldComponentUpdate() {
return false;
}
changeColor = () => {
this.setState({favoritecolor: "blue"});
}
render() {
return (
<div>
<h1>My Favorite Color is {this.state.favoritecolor}</h1>
<button type="button" onClick={this.changeColor}>
Change color</button>
</div>
);
}
}
This example has a button that changes the favorite color
to blue, but since the shouldComponentUpdate() method
is called, the favorite color is still rendered as red
(because the method returns false).

•getSnapshotBeforeUpdate()
BINDHYA PS , MBCET 65
The getSnapshotBeforeUpdate() method is invoked just before the DOM is being rendered.
It is used to store the previous values of the state after the DOM is updated.
getSnapshotBeforeUpdate(prevProps, prevState)
It receives previous props and previous state as parameters.
It must return a value, or null.
The return value is passed as the third argument to componentDidUpdate().

•getSnapshotBeforeUpdate()
BINDHYA PS , MBCET 66
•It runs just before the DOM is updated (after render(), before componentDidUpdate()).
•It capture information from the DOM or props/state before they change
Example: Flow of Execution
Initial render → color = red.
After 1 second → state updates to yellow.
getSnapshotBeforeUpdate() runs → captures previous color (red).
DOM updates to show yellow.
componentDidUpdate() runs → uses snapshot to show what it was before.

•getSnapshotBeforeUpdate()
BINDHYA PS , MBCET 67
class Header extends React.Component {
constructor(props) {
super(props);
this.state = {favoritecolor: "red"};
}
componentDidMount() {
setTimeout(() => {
this.setState({favoritecolor: "yellow"})
}, 1000)
}
getSnapshotBeforeUpdate(prevProps, prevState) {
document.getElementById("div1").innerHTML =
"Before the update, the favorite was " + prevState.favoritecolor;
}

componentDidUpdate() {
document.getElementById("div2").innerHTML =
"The updated favorite is " + this.state.favoritecolor;
}
render() {
return (
<div>
<h1>My Favorite Color is {this.state.favoritecolor}</h1>
<div id="div1"></div>
<div id="div2"></div>
</div>
);
}
}

•componentDidUpdate()
BINDHYA PS , MBCET 68
It is called immediately after a component updates (re-renders because of state/props change).

This function is invoked after the component is rendered, i.e., this function gets invoked once
after the render() function is executed after the updation of State or Props.
componentDidUpdate(prevProps, prevState, snapshot)

•componentDidUpdate()
BINDHYA PS , MBCET 69
It is called immediately after a component updates (re-renders because of state/props change).

This function is invoked after the component is rendered, i.e., this function gets invoked once
after the render() function is executed after the updation of State or Props.
componentDidUpdate(prevProps, prevState, snapshot)

Unmounting
BINDHYA PS , MBCET 70
This is the final phase of the lifecycle of the component, which is the phase of
unmounting the component from the DOM.

componentWillUnmount()
This function is invoked before the component is finally unmounted from the DOM,
i.e., this function gets invoked once before the component is removed from the page,
and this denotes the end of the lifecycle.

Implementing the Component Lifecycle methods Next slide

import React from 'react';
import ReactDOM from 'react-dom';
class SimpleLifecycle extends React.Component {
constructor(props) {
super(props);
this.state = { message: "Hello, World!" };
console.log("constructor: initializing state"); }
componentDidMount() {
console.log("component mounted");
}
shouldComponentUpdate(nextProps, nextState) {
console.log(“Deciding to update"); return true;
}
BINDHYA PS , MBCET 71
componentDidUpdate(prevProps, prevState) {
console.log(“Component updated");
}
componentWillUnmount() {
console.log("cleanup before unmounting");
}
changeMessage = () => {
this.setState({ message: "React Lifecycle Example!" }); };
render() {
console.log(“Rendering component");
return ( <div>
<h1>{this.state.message}</h1>
<button onClick={this.changeMessage}>Change
Message</button>
</div> );
}} ReactDOM.render(<SimpleLifecycle />,
document.getElementById('root'));

What are hooks?
Built-in hooks:
•useState
•useEffect
•useReducer
•useMemo
•useRef
•useCallback
BINDHYA PS , MBCET 72
Hooks allow functions to have access to state and other React features
without using classes. They provide a more direct API to React concepts like
props, state, context, refs, and lifecycle.
There are 3 rules for hooks:
•Hooks can only be called inside React function components.
•Hooks can only be called at the top level of a component.
•Hooks cannot be conditional

Note: Hooks will not work in React class components.

useState Hook
•The useState hook is used to declare state variables in functional components.
•It allows us to read and update the state within the component.

BINDHYA PS , MBCET 73
To use the useState Hook, first import it into our component.
import { useState } from "react";

Using State in Functional Component (with useState)
import React, { useState } from "react";
function Counter()
{
const [count, setCount] = useState(0);
const increment = () => setCount(count + 1);
const decrement = () => setCount(count - 1);
return ( <div>
<h1>Count: {count}</h1>
<button onClick={increment}>Increment</button>
<button onClick={decrement}>Decrement</button>
</div> );
}export default Counter;
74

Using State in Functional Component (with useState)
import React, { useState } from 'react';
export default function favColor() {
const [color, setColor] = useState("red ");
return (
<div style={{ textAlign: "center", marginTop: "50px" }} >
<p>My favourite colour is {color}.</p>
<button type= "button " onClick={()=>setColor(" blue ")}>
Click me
</button>
</div>
);}
75

useEffect
•The Effect Hook, useEffect, adds the ability to perform side effects from a function
component.
•Some examples of side effects are: fetching data, directly updating the DOM, and timers.
•The useEffect accepts two arguments. The second argument is optional.
import {useEffect } from "react";
useEffect(callback, [dependencies]);

Before hooks, these kinds of tasks were only possible in class components through lifecycle methods
like componentDidMount, componentDidUpdate, and componentWillUnmount.

useEffect
Syntax:
useEffect(() => {
// Code to run on each render
return () => {
// Cleanup function (optional)
};
}, [dependencies]);
77
•Effect function: This is where your side effect code runs.
•Cleanup function: This optional return function cleans up side effects like subscriptions or timers when the
component unmounts.
•Dependencies array: React re-runs the effect if any of the values in this array change

Example 1: Run effect after every render (no dependencies)
import React, { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
useEffect(() => {
console.log("Effect runs after every render");
});
return (<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button> </div>
);}
78

Example 2: Run effect only once on component mount
(empty dependency array)
import React, { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
useEffect(() => {
console.log("Effect runs only once after initial render");
}, []);
return (<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button> </div>
);}
79

Example 3: Run effect when specific value(s) change
import React, { useState, useEffect } from 'react';
function Example() {
const [name, setName] = useState('React');
useEffect(() => {
console.log(`Effect runs when name changes: name=${name}`);
}, [name]);

return (
<div>
<input value={name} onChange={event => setName(event.target.value)} />
</div>
););}
80

React Conditional Rendering
Conditional rendering means rendering different UI elements or components depending on some
conditions (like state, props).
Common Techniques:
if-else statement
Ternary operator (condition ? true : false)
Logical AND (&&): Render element only if condition is true

81

if Statement
•if JavaScript operator to decide which component to render.
BINDHYA PS , MBCET 82
function Greeting(props) {
if (props.isLoggedIn) {
return <h1>Welcome Back!</h1>;
}
return <h1>Please Log In</h1>;
}
App.js
<Greeting isLoggedIn={true} />

Using if-else Statement
BINDHYA PS , MBCET 83
function Status({isOnline}) {
let message;
if (isOnline) {
message = "User is Online";
} else {
message = "User is Offline";
}
return <h2>{message}</h2>;}

Using Ternary Operator
BINDHYA PS , MBCET 84
function Greeting({ isLoggedIn }) {
return (
<h1>
{isLoggedIn ? 'Welcome back!' : 'Please sign in.'}
</h1>
);
}
condition ? true : false

Using Logical AND (&&) Operator
BINDHYA PS , MBCET 85
function Cart({ items }) {

return ( <div>
<h2>Your Cart</h2>
{items.length > 0 && <p>You have {items.length} items in your cart.</p>}
</div> );
}
If items.length > 0, it shows the message; otherwise, nothing is displayed.

React Router
BINDHYA PS , MBCET 86

Components of React Router
1.BrowserRouter and HashRouter
•BrowserRouter: Uses the HTML5 history API to keep your UI in sync with the URL.
•HashRouter: Uses the hash portion of the URL (i.e., window.location.hash) to keep your
UI in sync with the URL.
<BrowserRouter>
(/* Your routes go here */}
</BrowserRouter>
BINDHYA PS , MBCET 87

Components of React Router
2. Routes and Route
•Routes: A container for all your route definitions.
•Route: Defines a single route with a path and the component to render.
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
BINDHYA PS , MBCET 88

Components of React Router
3. Link and NavLink
• Link: Creates navigational links in your application.
• NavLink: Similar to Link but provides additional styling attributes when the link is active.
<nav>
<NavLink to="/" activeClassName="active">Home</NavLink>
<Link to="/about">About</Link>
</nav>

NavLink supports activeClassName which applies the specified CSS class when the
link route is active.
BINDHYA PS , MBCET 89

React Router
•React Router is a JavaScript library designed specifically for React to handle
client-side routing.
•It maps specific URL paths to React components, allowing users to navigate
between different pages or sections without refreshing the entire page.
BINDHYA PS , MBCET 90
npm install react-router-dom
This installs React Router DOM which contains components for routing in web apps.
1.Install React Router

React Router
2.Setup React Router in Your App
In your src/index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import { BrowserRouter } from 'react-router-dom';
import App from './App';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render( <BrowserRouter>
<App />
</BrowserRouter>);
BINDHYA PS , MBCET 91
You can use {BrowserRouter}
in Apps.js also

React Router
3.Define Routes in App Component
In your src/App.js
import React from 'react';
import { Routes, Route, Link } from 'react-router-dom';
function Home() {
return <h1>Home Page</h1>;
}
function About() {
return <h1>About Page</h1>;
}
BINDHYA PS , MBCET 92
function App() {
return ( <div>
<nav>
<Link to="/">Home</Link> | {" "}
<Link to="/about">About</Link>
</nav>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</div>
);
}export default App;

Context API
•Context API is a way to share data across components without
having to pass props manually through every level. (called “prop
drilling”).
•Context API solves these problems by:
- Eliminating the need to pass props through intermediate components
- Providing a central place to store and manage shared state
- Making components more reusable and maintainable
BINDHYA PS , MBCET 93

BINDHYA PS , MBCET 94

Steps to Implement Context API in React
1.Create Context - Use createContext() to create a context object.This object will hold the shared data.
import { createContext } from "react";
const MyContext = createContext();
2.Provide Context - Wrap your components inside Context.Provider.

BINDHYA PS , MBCET 95
<MyContext.Provider value={"WELCOME EVERYONE"}>
<ChildComponent />
</MyContext.Provider>
Anything inside <Provider> can now access the value.

Steps to Implement Context API in React
3.Consume
•Class: static contextType = MyContext; this.context
•Function: const data = useContext(MyContext);
BINDHYA PS , MBCET 96
Anything inside <Provider> can now access the value.

CONTEXT API - EXAMPLE
import React, { createContext } from "react";
const MyContext = createContext(); // Step 1: create context

export default class App extends Component {
state = { user: “ABC", };

render() {
return (
<MyContext.Provider value={this.state.user}> //step 2: provide context
<div>
<h1>App Component</h1>
<Child /> //function call
</div>
</MyContext.Provider>
);
}
}
BINDHYA PS , MBCET 97

CONTEXT API - EXAMPLE
class Child extends Component {
static contextType = MyContext; // Step 3: consume
render() {
return <h2>Hello, {this.context}</h2>;
}
}
BINDHYA PS , MBCET 98

BINDHYA PS , MBCET 99

Comparison
BINDHYA PS , MBCET 100

BINDHYA PS , MBCET 101
THANKYOU
Tags