0% found this document useful (0 votes)
17 views83 pages

WDF Unit 3 Digital Notes

This document outlines the course structure for 'Web Development Frameworks' offered by RMK Group of Educational Institutions for the batch 2023-2027. It includes details on course objectives, prerequisites, syllabus, course outcomes, and a mapping of course outcomes to program outcomes. Additionally, it lists faculty members involved, lecture plans, and resources for students, emphasizing hands-on experience with modern web development technologies like ReactJS.

Uploaded by

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

WDF Unit 3 Digital Notes

This document outlines the course structure for 'Web Development Frameworks' offered by RMK Group of Educational Institutions for the batch 2023-2027. It includes details on course objectives, prerequisites, syllabus, course outcomes, and a mapping of course outcomes to program outcomes. Additionally, it lists faculty members involved, lecture plans, and resources for students, emphasizing hands-on experience with modern web development technologies like ReactJS.

Uploaded by

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

Please read this disclaimer before proceeding:

This document is confidential and intended solely for the educational purpose of
RMK Group of Educational Institutions. If you have received this document
through email in error, please notify the system manager. This document
contains proprietary information and is intended only to the respective group /
learning community as intended. If you are not the addressee you should not
disseminate, distribute or copy through e-mail. Please notify the sender
immediately by e-mail if you have received this document by mistake and delete
this document from your system. If you are not the intended recipient you are
notified that disclosing, copying, distributing or taking any action in reliance on
the contents of this information is strictly prohibited.
22IT407
WEB DEVELOPMENT FRAMEWORKS
(Lab Integrated)
Batch / Year / Semester: 2023-2027 / II / 4

Name of the Faculty Members


RMKEC
1.Dr. S.D. Lalitha, ASP, CSE, RMKEC
2.Ms. V. Haritha, AP, CSE, RMKEC
3.Ms. J. Latha, AP, CSE,RMKEC
4.Dr. G. Manikandan, Professor, ADS, RMKEC
5.Dr. Gladiss Merlin N R, ASP, ADS, RMKEC
6.Dr. A. Ponmalar, ASP, ADS,RMKEC
7.Dr. P. Umaeswari, ASP, CSBS, RMKEC
8.Dr. M.S. Girija ,ASP,CSD,RMKEC
9.Ms. M. Kanniga Parameshwari, AP ,IT, RMKEC
RMDEC
1.Dr. G. Amudha , Professor & Head, CSBS, RMDEC
2.Dr. P.M. Joe Prathap , Professor, CSE, RMDEC
3.Mrs. D. Vishnu Sakthi , AP, CSE, RMDEC
4.Dr. K. Roslin Dayana, ASP, CSE, RMDEC
5.Dr. R .Jothilakshmi , ASP, IT, RMDEC
6.Dr. B. Kalpana, ASP, IT, RMDEC
7.Dr. K. Sudharson, ASP, AIML, RMDEC
8.Dr. K. Sudha, ASP, CSBS, RMDEC
RMKCET
1.Dr. Sivasubramanian R , ASP, CSE, RMKCET
2.Dr. Prasath R, ASP, CSE, RMKCET
3.Ms. Saranya R, ASP, CSE, RMKCET
4.Dr. L. Maria Michael Visuwasam, ASP, ADS, RMKCET

4
1. CONTENTS
S.NO. CONTENTS PAGE NO

1 Contents 5
2 Course Objectives 6
3 Pre Requisites 7
4 Syllabus 8
5 Course Outcomes 13
6 CO- PO/PSO Mapping 14
7 Lecture Plan 15
8 Activity Based Learning 16
9 Lecture Notes 18-56
10 Assignment – 1 to 5 57-58
11 Part A Questions & Answers 59-73
12 Part B Questions 74
Supportive Online Certification 75
13
Courses
14 Real time Applications 76-77
15 Contents Beyond the Syllabus 78
16 Assessment Schedule 80
Prescribed Text Books & Reference 81
17
Books
18 Mini Project – 1 to 5 82

5
2. COURSE OBJECTIVES
OBJECTIVES:

The Course will enable learners:

● To understand web semantics and related tools and


framework

● Able to get hands on latest JS based web frameworks

● To develop a scalable and responsive web application

● To develop an industry ready application web enterprise


feature

6
3. PRE REQUISITES
• Pre-requisite Chart

22IT407

WEB DEVELOPMENT FRAMEWORKS

22CS102
-
SOFTWARE DEVELOPMENT PRACTICES

7
4. Syllabus
22IT407 – WEB DEVELOPMENT FRAMEWORKS (Lab Integrated) – L T P C - 3 0 2 4

UNIT I - ADVANCED JAVASCRIPT – 9+6


Introduction to HTML5 and CSS3, Media Queries, JS, DOM, BootStrap, Variables, Loops,
Operators, Scope, Hoisting, Arrays, Spread, REST, DeStructuring.
List of Exercise/Experiments
1) Create a JS Object for Bank Account (w attributes like à customer name,
account type, balance, data of creation, bank name, branch name, pan card
number). Using JS Object keyword, try to perform following activities
➢ List down all the entries of the bank object
➢ Check the existence of a key
➢ If key found, get the value for the key
2) Spread Operator
➢ Merge Customer and Account Arrays
➢ Update the Customer Object with the new values
➢ Develop a function that takes a Spread Argument and calculates total balance.
UNIT II - INTRODUCTION TO REACTJS - 9+6
Class-Inheritance, Methods, Extended Class-Map, filter and Reduce Functions, Functions -
Arrow Functions, Lambda Expressions, REST - Introduction, Why JSX, Hello World Apps,
Project Structure
List of Exercise/Experiments
1) Create a list of Bank Objects (same kind of object you used in above
lab, but in an array format)
➢ Display the banks where balance is greater than 200
➢ deduct 10% of the Bank account balance, as part of monthly service
fees
➢ Display the banks where balance is greater than 200 and branch
code is “Chennai”
➢ Add a new Bank to the given array
➢ Delete a bank from the array (use splice operator)
➢ Calculate the total balance of all bank accounts

6
4. Syllabus
2) Develop a Scientific calculator that does following operations
➢ Rounded Value
➢ Area of Circle
➢ Calculating of Sin, Cos and Tan functions
➢ Permiter of a Rectangle
➢ Employ Arrow functions
➢ Employ HOC
UNIT III - REACT COMPONENTS – 9+6
Class vs Functional Components, Lifecycle methods - React Class Based Components
– component DidMount, WillUpdate, shouldupate, didcatchetc - State - UseState,
UseRef, USeEffect, UseHistory Usage and Props(difference, when to use what,
mutable or immutabilty,direction of flow), PropTypes, Auxillary Components,
Controlled and Uncontrolled Components, Component Interaction (Parent to Child and
Child to Parent), Iteration & Conditional Response
List of Exercise/Experiments
1) Create a collection of Customer by using
➢ Weak Map and Map Collection in JS
➢ Show Case the different feature set of the same.
2) Add Login Page, Dash Board Page, Admin Page
➢ Enable React Routing
➢ Add React Protected Route, for authorization
UNIT IV - REACT LIBRARY – I – 9+6
Event Bubbleup - Component Wrapper - Integration of CSS Modules - Forms
Validations(YUP, Formik, Standard), Events Handling, Data Binding - Redux
List of Exercise/Experiments
1) Develop a React application that has User Registration Form w field
level validations, data submission to a rest api end point, boot strap for
responsive.
➢ Use YUP or Formik to implement the same.
4. Syllabus
2) Build a Redux Counter Application
Requirements:
➢ React application with Redux integrated.
➢ A counter with:
➢ Increment button
➢ Decrement button
➢ Reset button
➢ Display the current counter value.
UNIT V - REACT LIBRARY – II – 9+6
Custom Hooks, HTTP - Fetch, Axios, and Context API, Services, Behaviour Subjects -
StateLess, StateFulll and Container Components, Error Handling - Build, Env, CORS, Unit
Testing w React Testing Library - Introduction to react-native - Introduction to StoryBook
List of Exercise/Experiments
1) Employ backend API for Login Page functionality (authentication). Post login,
store the user context (received from the back end server) in browser’s session
storage as objects. And use the same as creds during protected route verification.
➢ On the dashboard page, have a grid of Students. The data has to be bought
from backend api
➢ Employ useref, useeffect & usestate, and useHistory
2) Enable Exception Handling
3) Enable HOC and Aux Components
4) Implement React-Testing Library
5) Basic Context Setup
Objective: Set up a React Context to manage theme (light or dark).
➢ Create a ThemeContext using React.createContext.
➢ Create a provider component ThemeProvider with state to toggle
between "light" and "dark" themes.
➢ Use the context in a functional component to display the current theme.
➢ Add a button to toggle the theme.
4. SYLLABUS
Business Use Case Implementations

1) Student Management System

2) Retail Bank System

3) E-Commerce System
4) Student LMS Management System
TOTAL:45+30=75 PERIODS
TEXTBOOK:
1. David Flanagan, Javascript The Definitive Guide, Paperback, 7th Edition, 2020.
2. David Choi ,Full-Stack React, TypeScript, and Node: Build cloud-ready web
applications using React 17 with Hooks and GraphQL Paperback – Import, 18
December 2020.
3. Mehul Mohan, Advanced Web Development with React Paperback – 1 January
2020.
E-RESOURCES:
1.Parental Website - https://reactjs.org/
2.The Road to Learn React: Your journey to master plain yet pragmatic React.js by
Robin Wieruch
3.Learning React: Functional Web Development with React and Redux by Alex Banks
and Eve Porcello
4. Learning React by KirupaChinnathambi
5. "React Up & Running" by StoyanStefanov
6. https://www.edureka.co/reactjs-redux-certification-training
7. CodePen
8. CodeSandbox (Preferred)
9. Stackblitz

11
4. SYLLABUS
LIST OF EQUIPMENTS:
• NodeJS (v9.11.2)
• Github as code repository
• Visual studio code as IDE
• RTL as unit testing framework
• Responsive design w bootstrap
• ReactJS installation (v17)
• Chrome / FIreFox Browsers (latest)
• Responsive using Media Queries & Bootstrap Material & Antdesign
• Design based Apps.

12
5. Course Outcomes
Course Outcomes with Knowledge Levels:
CO1: Personalize web pages using text formatting, graphics, audio,
and video. - K3
CO2: Hands on knowledge on Rest API , propTypes. - K3
CO3: Able to develop a web application using latest React
Framework – K3
CO4: Apply various React features including functions,
components, and services. – K3
CO5: Able to develop application using ReactJshooks. – K3
CO6: Design and integrate complex web components to enhance
user interface and user experience in React applications. – K5

11
6. CO-PO/PSO Mapping

PROGRAM OUTCOMES PSO


CO
PO PO PO PO PO PO PO PO PO PO PO PO P P P
S S S
1 2 3 4 5 6 7 8 9 10 11 12 O O O
1 2 3
CO1 3 3 3 1 1 - - - 2 1 - 1 3 3 1

CO2 3 2 3 1 2 - - - 2 1 - 1 3 3 1

CO3 3 3 3 1 2 - - 1 2 1 - 1 3 3 1

CO4 3 3 3 1 2 - - - 2 1 - 1 3 3 1

CO5 3 3 3 1 2 - - 1 2 1 - 1 3 3 1

CO6 2 3 3 - 3 - - 1 2 2 - 3 3 3 1

CO 2.83 2.83 3.00 1.00 2.00 - - 1.00 2.00 1.17 - 1.33 3.00 3.00 1.00

Correlation Level
1. Slight (Low)
2. Moderate (Medium)
3. Substantial (High) ,
If there is no correlation, put “-“.

12
7. LECTURE PLAN
Sl. Taxono
No. of. Proposed Actual Pertaining Mode of
No Topics my
Periods Date Date CO Delivery
. Level

As per As per
Class vs Functional CO3, MD 1,
1 1 academic academic K3
Components CO4,CO5 MD 4
calendar calendar

Lifecycle methods - As per As per


CO3, MD 1,
2 React Class Based 1 academic academic K3
CO4,CO5 MD 4
Components calendar calendar
component
DidMount, As per As per
CO3, MD 1,
3 WillUpdate, 1 academic academic K3
CO4,CO5 MD 4
shouldupate, calendar calendar
didcatchetc

As per As per
State - UseState, CO3, MD 1,
4 1 academic academic K3
UseRef, CO4,CO5 MD 4
calendar calendar

USeEffect,UseHisto
ry Usage and
Props(difference, As per As per
CO3, MD 1,
5 when to use what, 1 academic academic K3
CO4,CO5 MD 4
mutable or calendar calendar
immutabilty,
direction of flow)
PropTypes, As per As per
CO3, MD 1,
6 Auxillary 1 academic academic K3
CO4,CO5 MD 4
Components calendar calendar
Controlled and As per As per
CO3, MD 1,
7 Uncontrolled 1 academic academic K3
CO4,CO5 MD 4
Components calendar calendar
Component
As per As per
Interaction (Parent CO3, MD 1,
8 1 academic academic K3
to Child and Child CO4,CO5 MD 4
calendar calendar
to Parent)
Iteration &
As per As per
Conditional CO3, MD 1,
9 1 academic academic K3
Response CO4,CO5 MD 4
calendar calendar

10 As per As per
CO3,
- Lab Exercises 6 academic academic K3 iamneo
CO4,CO5
15 calendar calendar

* MD1 – Oral Presentation


* MD 4 – Hands on using any IDE
8. Activity Based Learning

Common Activities

Learning Methods Activities

Class Exercises, Challenge Yourself,


Learn by Solving Problems Practice At Home exercises posted in
iamneo Portal

Knowledge Check / MCQ Using


Learn by Questioning
iamneo portal and RMK Nextgen App

Learn by Hands on Practice available in iamneo Portal


8. Activity Based Learning
Unit III Activity
The basic idea is that the game will present the user with a grid of randomly
appearing balloons, and the objective is to pop them to earn points. Each
successful balloon pop will reward the player with five points:

Check out this live CodePen demo to preview what you will build. Or, explore the
complete code from the GitHub repo of this project.
Lecture Notes

Unit III - REACT COMPONENTS

Class vs Functional Components, Lifecycle methods - React


Class Based Components – component DidMount,
WillUpdate, shouldupate, didcatchetc - State - UseState,
UseRef, USeEffect,UseHistory Usage and Props(difference,
when to use what, mutable or immutabilty,direction of flow),
PropTypes, Auxillary Components, Controlled and
Uncontrolled Components,Component Interaction (Parent to
Child and Child to Parent), Iteration & Conditional Response
9. LECTURE NOTES
3. INTRODUCTION TO COMPONENTS

A Component is one of the core building blocks of React. In other words, we can say that
every application you will develop in React will be made up of pieces called components.
Components make the task of building UIs much easier. You can see a UI broken down into
multiple individual pieces called components and work on them independently and merge
them all in a parent component which will be your final UI.
You can see in the below image we have broken down the UI of GeeksforGeeks’s homepage
into individual components.

3.1 TYPES OF COMPONENTS IN REACTJS

Components in React basically return a piece of JSX code that tells what should be rendered
on the screen.
Types of components in ReactJS.
In React, we mainly have two types of components:

3.2 FUNCTIONAL BASED COMPONENTS


Functional components are simply javascript functions. We can create a functional
component in React by writing a javascript function. These functions may or may not receive
data as parameters,
The below example shows a valid functional component in React:

function demoComponent() {
return (<h1>
Welcome Message!
</h1>);
}

3.3 CLASS BASED COMPONENTS


The class components are a little more complex than the functional components. The
functional components are not aware of the other components in your program whereas the
class components can work with each other. We can pass data from one class component to
another class component. We can use JavaScript ES6 classes to create class-based
components in React. The below example shows a valid class-based component in React:

class Democomponent extends React.Component {


render() {
return <h1>Welcome Message!</h1>;
}
}
❑ The components we created in the above two examples are equivalent, and we also have
stated the basic difference between a functional component and a class component. We
will learn about more properties of class-based components in further tutorials.
❑ For now, keep in mind that we will use functional components only when we are sure that
our component does not require interacting or work with any other component. That is,
these components do not require data from other components however we can compose
multiple functional components under a single functional component.
❑ We can also use class-based components for this purpose but it is not recommended as
using class-based components without need will make your application in-efficient.
"Rendering Components in ReactJS”

React is also capable of rendering user-defined components. To render a component in React


we can initialize an element with a user-defined component and pass this element as the first
parameter to ReactDOM.render() or directly pass the component as the first argument to the
ReactDOM.render() method.
The below syntax shows how to initialize a component to an element:
const elementName = <ComponentName />;

In the above syntax, the ComponentName is the name of the user-defined component.
Note: The name of a component should always start with a capital letter. This is done to
differentiate a component tag from HTML tags.
The below example renders a component named Welcome to the Screen:
Open your index.js file from your project directory, and make the given below changes:
src index.js:

import React from 'react';


import ReactDOM from 'react-dom';

// This is a functional component


const Welcome = () => {
return <h1>Hello World!</h1>
}

ReactDOM.render(
<Welcome />,
document.getElementById("root")
);
❑ Let us see step-wise what is happening in the above example:
❑ We call the ReactDOM.render() as the first parameter.
❑ React then calls the component Welcome, which returns <h1>Hello World!</h1>; as the
result.
❑ Then the ReactDOM efficiently updates the DOM to match with the returned element and
renders that element to the DOM element with id as “root”.

Components let you split the UI into independent, reusable pieces, and think about each
piece in isolation. This page provides an introduction to the idea of components.
Conceptually, components are like JavaScript functions. They accept arbitrary inputs (called
“props”) and return React elements describing what should appear on the screen.

Note: Always start component names with a capital letter.


React treats components starting with lowercase letters as DOM tags. For
example, <div /> represents an HTML div tag, but <Welcome /> represents a
component and requires Welcome to be in scope.
To learn more about the reasoning behind this convention, please read JSX In
Depth.

Composing Components
Components can refer to other components in their output. This lets us use the same
component abstraction for any level of detail. A button, a form, a dialog, a screen: in React
apps, all those are commonly expressed as components.
For example, we can create an App component that renders Welcome many times:

function Welcome(props) {
return <h1>Hello, {props.name}</h1>; }
function App() {
return ( <div> <Welcome name="Sara" /> <Welcome name="Cahal" /> <Welcome
name="Edite" /> </div> ); }
Extracting Components
function Comment(props) {
return (
<div className="Comment">
<div className="UserInfo">
<img className="Avatar" src={props.author.avatarUrl} alt={props.author.name} />
<div className="UserInfo-name"> {props.author.name} </div>
</div>
<div className="Comment-text"> {props.text} </div>
<div className="Comment-date"> {formatDate(props.date)} </div>
</div> ); }
• 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.

import React, { Component } from 'react';


class App extends React.Component {
constructor() {
super();
this.state = {
data:
[
{
"name":“RMKEC"
},
{
"name":“RMDEC"
},
{
"name":“RMKCET"
}
]
}
}
render() {
return (
<div>
<StudentName/>
<ul>
{this.state.data.map((item) => <List data = {item} />)}
</ul>
</div>
);
}
}
class StudentName extends React.Component {
render() {
return (
<div>
<h1>COLLEGE DETAILS</h1>
</div>
);
}
}
class List extends React.Component {
render() {
return (
<ul>
<li>{this.props.data.name}</li>
</ul>
);
}
}
export default App;
React State

❑ The state is an updatable structure that is used to contain data or information about the
component. The state in a component can change over time. The change in state over time
can happen as a response to user action or system event. A component with the state is
known as stateful components. It is the heart of the react component which determines the
behavior of the component and how it will render. They are also responsible for making a
component dynamic and interactive.
❑ A state must be kept as simple as possible. It can be set by using the setState() method
and calling setState() method triggers UI updates. A state represents the component's local
state or information. It can only be accessed or modified inside the component or by the
component directly. To set an initial state before any interaction occurs, we need to use
the getInitialState() method.
❑ For example, if we have five components that need data or information from the state,
then we need to create one container component that will keep the state for all of them.

Defining State
To define a state, you have to first declare a default set of values for defining the
component's initial state. To do this, add a class constructor which assigns an initial state
using this.state. The 'this.state' property can be rendered inside render() method.
Example
The below sample code shows how we can create a stateful component using ES6 syntax.
import React, { Component } from 'react';
class App extends React.Component {
constructor() {
super();
this.state = { displayBio: true };
}

render() {
const bio = this.state.displayBio ? (
<div>
<p><h3>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.</h3></p>

</div>
) : null;
return (
<div>
<h1> Welcome to REACT CLASS</h1>
{ bio }
</div>
);
}
}
export default App;
• To set the state, it is required to call the super() method in the constructor. It is because
this.state is uninitialized before the super() method has been called.

Changing the State

We can change the component state by using the setState() method and passing a new
state object as the argument. Now, create a new method toggleDisplayBio() in the above
example and bind this keyword to the toggleDisplayBio() method otherwise we can't access
this inside toggleDisplayBio() method.
this.toggleDisplayBio = this.toggleDisplayBio.bind(this);

Example
In this example, we are going to add a button to the render() method. Clicking on this
button triggers the toggleDisplayBio() method which displays the desired output.
import React, { Component } from 'react';
class App extends React.Component {
constructor() {
super();
this.state = { displayBio: false };
console.log('Component this', this);
this.toggleDisplayBio = this.toggleDisplayBio.bind(this);
}
toggleDisplayBio(){
this.setState({displayBio: !this.state.displayBio});
}
render() {
return (
<div>
<h1>Welcome to REACT CLASS</h1>
{
this.state.displayBio ? (
<div>
<p><h4>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.</h4></p>
<button onClick={this.toggleDisplayBio}> Show Less </button>
</div>
):(
<div>
<button onClick={this.toggleDisplayBio}> Read More </button>
</div>
)
}
</div>
)
}
} export default App;
3.4 REACT COMPONENT LIFECYCLE METHODS

React is a JavaScript-based library for using component-based architecture to create


applications that share user interface content. It allows you to define the function or class-
based component that provides a specific feature for an application; hence, each component
in React application contains the set of lifecycle hooks. There are several lifecycle methods
such as mounting the component, updating the state of a component, or unmounting the
component.

Mounting
This phase of the component lifecycle is used to call the method when the instance of the
component can be created. It is also called while inserting the component into the HTML
DOM. There are a few methods used in the mounting phase;
constructor()
The constructor() method is called before anything else when the component is initiated, and it
is the natural place to set up the initial state and other initial values. This method is called with
the props as arguments, and you should always start by calling the super (props) before
anything else, this will initiate the parent’s constructor method and allows the component to
inherit methods from its parent (React.Component).

render()
Rendering is a crucial procedure programmer must manage in front end development. The
render() method is the only required method in a class component and is responsible for
describing the view to be rendered to the browser window. It is important to note that this
method is not user callable but is a part of the React Component Lifecycle. Within the lifecycle,
there are a number of scenarios when render is called;
After the React component is first instantiated, following the constructor() call.
After an update to the component’s props
After a setState() call

componentDidMount()
The componentDidMount() method enables us to execute the React code when the component
is already placed in the Document Object Model. All the AJAX requests and the DOM or state
updation should be coded in the componentDidMount() method block. After all the elements of
the page are rendered correctly, this method is called. After the markup is set on the page, this
technique is called by React itself to either fetch the data from an External API or perform some
unique operations which need the JSX elements.

Updating
This phase of the component lifecycle is triggered as soon as any changes are found in terms of
state or props that allow the DOM to be re-rendered again and again to update the DOM
elements. The updating phase includes several lifecycle hooks; requests.
getDerivedStateFromProps
This method is invoked right before calling the render method, both on the initial mount and on
subsequent updates. It should return an object to update the state, or null to update nothing.
The method exists for rare use cases where the state depends on changes in props over time.

shouldComponentUpdate ()
The shouldComponentUpdate () method may be used to let React know if a component’s output
is not affected by the current change in state or props. The default behaviour is to re-render on
every state change, and in the vast majority of cases, you should rely on the default behaviour.

componentDidUpdate ()
The componentDidUpdate method is called after the component is updated in the DOM. The
componentDidUpdate lifecycle method is invoked after the getSnapshotBeforeUpdate. As with
the getSnapshotBeforeUpdate method, it receives the previous props and state as arguments.
Whatever value is returned from the getSnapshotBeforeUpdate lifecycle method is passed as the
third argument to the componentDidUpdate method. nnecessary network

getSnapshotBeforeUpdate()
In the getSnapshotBeforeUpdate() method you have access to the props and state before the
update, meaning that even after the update, you can check what values were before the update.
If the getSnapshotBeforeUpdate() method is present, you should also include the
componentDidUpdate() method, otherwise, you will get an error.

Unmounting
The unmounting phase begins when an existing component is removed from the DOM. It
includes a single and important lifecycle hook, componentWillUnmount().

Error Handling
This is one of the most crucial phases of the component, error handling is used to trigger an
action in case of an error during the component rendering. There are two methods used to
manage the errors in the existing component;
ComponentDidCatch()
ComponentDidCatch() was added in React 16 and is used in error boundaries. A component
becomes an error boundary if it defines the componentDidCatch method. In this method,
this.set State can be called and used to catch an unhandled Javascript error in a child
component tree and display a fallback UI instead of the component that crashed. These
errors are caught during rendering, in lifecycle methods, and in constructors of the whole
tree below them.

Static GetDerivedStateFromError()
This is a complete list of lifecycle phases and component lifecycle hooks that trigger based
on each phase and component behaviour. Any of them can be chosen to trigger actions that
are reflected in the DOM. In this article, we shall put our emphasis on
ComponentDidUpdate(), one of the lifecycle methods under the updating stage.

How to Use ComponentDidUpdate()

❑ This lifecycle method gets called right after a change in props or a state change has
occurred. This might happen if new props have been provided by a parent component or
an internal state has been changed.
❑ The componentDidUpdate gets called after a render which means that you can access
DOM nodes in it. This function receives props and states as parameters. It can also
access new props and state with this.props and this.state. It provides the previous pros
and state values and in this way it allows you to do a comparison of a before and current
snapshot.
❑ Best use-cases of the ComponentDidUpdate() lifecycle;
✓ API calls after specific conditions have been met
✓ DOM manipulation after the component has been rendered.
✓ Update React state or stores like Redux and Mobx after a set of conditions have been
met.
❑ React Lifecycle triggers and events are designed to give developers the opportunity to
make decisions and take appropriate actions. A component goes through a series of
lifecycle events from when it is invoked to when it is destroyed. There are four triggers
that kick off these lifecycle events; Intiatilization, Updating State, Updating Props and
Unmounting. The componentDidUpdate event is triggered whenever there is a state or
props update.

❑ ComponentDidUpdate() has access to three properties, two of which are most often used
more than the third. These are prevProps, prevState and lastly, snapshot, which is used
less often. ComponentDidUpdate() is invoked immediately after updating occurs and is
not called for the initial render. The most common use-case for the componentDidUpdate
() lifecycle method is updating the DOM in response to Prop or State changes.

❑ ComponentDidUpdate() can also do network requests as long as current props are


compared to previous props. Essentially, a network request may not be necessary if props
haven’t changed. You can call setState() immediately in a componentDidUpdate as long as
it's wrapped up in a conditional statement.

❑ ComponentDidUpdate() is majorly used to perform some operations which need to be


executed only if the DOM is updated. To avoid any performance issues, it is advised to use
this method with conditional loop;

❑ The componentDidUpdate is also particularly useful when an operation needs to happen


after the DOM is updated and the update queue is emptied. It’s probably most useful on
complex renders and state or DOM changes or when you need something to be the
absolute last thing to be executed.

❑ This updating method is also the best point in the lifecycle to perform an interaction with
a non-React environment like the browser or making HTTP requests. This should be done
as long as you compare the current props to the previous props to avoid u
3.5 REACT STATES
Consider the ticking clock example from one of the previous sections. In Rendering Elements,
we have only learned one way to update the UI. We call root.render() to change the rendered
output:
const root = ReactDOM.createRoot(document.getElementById('root'));
function tick() {
const element = (
<div> <h1>Hello, world!</h1>
<h2>It is {new Date().toLocaleTimeString()}.</h2>
</div> );
root.render(element);
}
setInterval(tick, 1000);

3.5.1 Adding Local State to a Class

Replace this.props.date with this.state.date in the render() method:


class Clock extends React.Component {
render() {
return (
<div> <h1>Hello, world!</h1>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
</div> );
}
}
3.5.2 Add a class constructor that assigns the initial this.state:
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {date: new Date()}; }
render() {
return (
<div> <h1>Hello, world!</h1> <h2>It is {this.state.date.toLocaleTimeString()}.</h2> </div>
); } }
Note how we pass props to the base constructor:
constructor(props) {
super(props); this.state = {
date: new Date()};
}
Class components should always call the base constructor with props.
3.5.3 Remove the date prop from the <Clock /> element:
root.render(<Clock />);

3.6 ) REACTJS HOOKS

Hooks are a new addition in React 16.8. They let you use state and other React features
without writing a class.
import React, { useState } from 'react';
function Example() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);
return (
<div> <p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}> Click me </button>
</div> );
}
Before we continue, note that Hooks are:
• Completely opt-in. You can try Hooks in a few components without rewriting any existing
code. But you don’t have to learn or use Hooks right now if you don’t want to.
• 100% backwards-compatible. Hooks don’t contain any breaking changes.
• Available now. Hooks are now available with the release of v16.8.0.
• There are no plans to remove classes from React. You can read more about the gradual
adoption strategy for Hooks in the bottom section of this page.
• Hooks don’t replace your knowledge of React concepts. Instead, Hooks provide a more direct
API to the React concepts you already know: props, state, context, refs, and lifecycle.
3.6.1 ) UseState HOOKS
Voting.js
import { useState } from "react";
export function Voting(props) {
const [like, setLike] = useState(0);
const [dislike, setDislike]=useState(0);
return (
<div className="Votes"
style = {like>dislike?{background:"green"}:{background:"yellow"}}>
<h1>{props.brandname}</h1>
<h4>{props.Model}</h4>

<button onClick={() => setLike(like + 1)}> {like}</button>


<button onClick={() => setDislike(dislike + 1)}> {dislike}</button>
</div>
);
}
App.js
import logo from "./logo.svg";
import "./App.css";
import { Voting } from "./Voting";
function App() {
const brands = [
{
name: "Samsung",
model: "S12",
},
{
name: "Apple",
model: "I14Pro",
},
{

name: "OnePlus",

model: "O14",

},

];

return (

<div>

{/* <Voting brandname="Samsung" Model="S12"/>

<Voting brandname="Apple" Model="I14"/>

<Voting brandname="Oneplus" Model="O13"/>

<Voting brandname="Redmi" Model="R13Pro"/> */}

{brands.map((mob) => (

<Voting brandname={mob.name} model={mob.model} />

))}

</div>

);

}
export default App;
Here, useState is a Hook (we’ll talk about what this means in a moment). We call it inside a
function component to add some local state to it. React will preserve this state between re-
renders. useState returns a pair: the current state value and a function that lets you update it.
You can call this function from an event handler or somewhere else. It’s similar
to this.setState in a class, except it doesn’t merge the old and new state together. (We’ll show
an example comparing useState to this.state in Using the State Hook.)
Declaring multiple state variables

You can use the State Hook more than once in a single component:

function ExampleWithManyStates() {

// Declare multiple state variables!

const [age, setAge] = useState(42);

const [fruit, setFruit] = useState('banana');

const [todos, setTodos] = useState([{ text: 'Learn Hooks' }]);

// ...

The array destructuring syntax lets us give different names to the state variables we
declared by calling useState. These names aren’t a part of the useState API. Instead, React
assumes that if you call useState many times, you do it in the same order during every
render.

But what is a Hook?

Hooks are functions that let you “hook into” React state and lifecycle features from function
components. Hooks don’t work inside classes — they let you use React without classes.
React provides a few built-in Hooks like useState. You can also create your own Hooks to
reuse stateful behavior between different components.

3.6.2 ) UseEffect HOOKS

The Effect Hook, useEffect, adds the ability to perform side effects from a function
component. It serves the same purpose as componentDidMount, componentDidUpdate,
and componentWillUnmount in React classes, but unified into a single API. (We’ll show
examples comparing useEffect to these methods in Using the Effect Hook.)
For example, this component sets the document title after React updates the DOM:

import React, { useState, useEffect } from 'react';

function Example() {

const [count, setCount] = useState(0);

// Similar to componentDidMount and componentDidUpdate:

useEffect(() => {

// Update the document title using the browser API

document.title = `You clicked ${count} times`; });

return (

<div> <p>You clicked {count} times</p>

<button onClick={() => setCount(count + 1)}>

Click me

</button>

</div>

);

}
❑ When you call useEffect, you’re telling React to run your “effect” function after flushing
changes to the DOM. Effects are declared inside the component so they have access to
its props and state. By default, React runs the effects after every render —
including the first render. (We’ll talk more about how this compares to class lifecycles
in Using the Effect Hook.)
❑ Effects may also optionally specify how to “clean up” after them by returning a
function. For example, this component uses an effect to subscribe to a friend’s online
status, and cleans up by unsubscribing from it:
import React, { useState, useEffect } from 'react';

function FriendStatus(props)

const [isOnline, setIsOnline] = useState(null);

function handleStatusChange(status)

setIsOnline(status.isOnline);

useEffect(() => {

ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange); return () =>

ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange); };

);

if (isOnline === null)

return 'Loading...';

return isOnline ? 'Online' : 'Offline';

}
Rules of Hooks
❑ Hooks are JavaScript functions, but they impose two additional rules:
❑ Only call Hooks at the top level. Don’t call Hooks inside loops, conditions, or nested
functions.
❑ Only call Hooks from React function components. Don’t call Hooks from regular
JavaScript functions.
3.6.3 )React-Router HOOKS

React-Router is a popular React library that is heavily used for client-side routing and

offers single-page routing. It provides various Component APIs( like Route, Link, Switch,

etc.) that you can use in your React application to render different components based on

the URL pathnames in a single page.

Hooks Of React Router 5: React Router 5 offers 4 hooks that you can use in your react

applications:

✓ useHistory

✓ useParams

✓ useLocation

✓ useRouteMatch

1. useHistory:

This is one of the most popular hooks provided by React Router. It lets you access the

history instance used by React Router. Using the history instance you can redirect users

to another page. The history instance created by React Router uses a Stack( called

“History Stack” ), that stores all the entries the user has visited.

Syntax :

import { useHistory } from "react-router-dom"; // Inside a functional component export

default function SomeComponent(props){ // The useHistory() hook returns the history //

object used by React Router const history = useHistory(); }


Example:
Suppose we have a React project created using “create-react-app” having the following
project structure.
Project structure:

Suppose, inside the “LogIn.js”, we have a “LogIn” component that renders the log-in page.
The LogIn component renders two input fields, one for the username and another for a
password. When the user clicks the login button, we want to authenticate the user and
redirect the user to his/her profile page.
import { useHistory } from "react-router-dom";

import { useState } from "react";

// A function that authenticates the users

function authenticateUser(userName, password) {

// Some code to authenticate the user

// Hooks must be used inside a functional component

export default function Login(props) {

//Creating a state variable

const [userName, setUserName] = useState("");

const [password, setPassword] = useState("");

// Accessing the history instance created by React

const history = useHistory();

// Handle the user clicks the login button

const handleClick = () => {

// Authenticate the user

authenticateUser(userName, password);

// When the authentication is done

// Redirect the user to the `/profile/${userName}` page

// the below code adds the `/profile/${userName}` page

// to the history stack.

history.push(`/profile/${userName}`);

};
return (
<div>
<input
type="text"
value={userName}
onChange={(e) => {
setUserName(e.target.value);
}}
required
/>
<input
type="text"
value={password}
onChange={(e) => {
setPassword(e.target.value);
}}
required
/>
<button type="submit" onClick={handleClick}>
{" "}
Log In{" "}
</button>
</div>
);
}
2. useParams:
This hook returns an object that consists of all the parameters in URL.
import { useParams } from "react-router-dom"; // Inside a functional component export

default function SomeComponent(props){ const params = useParams(); }

These URL parameters are defined in the Route URL. For example,

<Route path="/profile/:userName" component={Profile} />The colon(“:”) after

“/profile/” specifies that “userName” is actually a variable or parameter that is dynamic.

For example, in the url “/profile/johndoe”, “johndoe” is the value of the parameter

“userName”. So, in this case, the object returned by useParams() is:

{ userName: "johndoe" }

Example: After the login we want our user to be redirected to the “profile/userName”

URL. The userName depends on the user’s given name. So, we need to set the URL

path dynamically based on the user given userName. This is easy to do, we need to

update the App.js file a little.

App.js

import { Route, Switch } from "react-router-dom";

import Home from "./components/Home";

import ContactUs from "./components/ContactUs";

import LogIn from "./components/LogIn";

import AboutUs from "./components/AboutUs";

import Profile from "./components/Profile";

export default function App() {

return (

<div className="App">
<Switch>

<Route path="/" exact>

<Home someProps={{ id: 54545454 }} />

</Route>

<Route path="/about">

<AboutUs />

</Route>

<Route path="/contact-us">

<ContactUs />

</Route>

<Route path="/log-in">

<LogIn />

</Route>

{/* userName is now a variable */}

<Route path="/profile/:userName">

<Profile />

</Route>

</Switch>

</div>

);

}
Profile.js

import {useParams} from "react-router-dom";

export default function Profile( props ) {

// useParams() returns an object of the parameters

// defined in the url of the page

// For example, the path given in the Route component

// consists of an "userName" parameter

// in this form ---> "/profile/:userName"

const { userName } = useParams();

return (

<div>

<h1> Profile of { userName }</h1>

<p> This is the profile page of { userName }</p>

</div>

);

Output: Now if you now go to the log-in page and click the login button with userName

“John”, then you will be redirected to the “profile/john” page.


3. useLocation:

This hook returns the location object used by the react-router. This object represents the

current URL and is immutable. Whenever the URL changes, the useLocation() hook

returns a newly updated location object. Some of its use includes extracting the query

parameters from the URL and doing something depending on the query parameters. The

“search” property of the location object returns a string containing the query part of the

URL.

Syntax :

import { useLocation } from "react-router-dom";

// Inside functional component export default function SomeComponent(props)

const location = useLocation();

Note: history.location also represents the current location, but it is mutable, on the other

hand, the location returned by useLocation() is immutable. So, if you want to use the

location instance, it is recommended to use the useLocation() hook.

Example: The useLocation() is very useful to get and use the query parameters defined

in the URL. In the below code we have used the useLocation hook to access the query

parameters. Then we parsed it using the URLSearchParams constructor.

import { useLocation } from "react-router-dom";

export default function Profile(props) {

const location = useLocation();

// location.search returns a string containing all


// the query parameters.
// Suppose the URL is "some-website.com/profile?id=12454812"
// then location.search contains "?id=12454812"
// Now you can use the URLSearchParams API so that you can
// extract the query params and their values
const searchParams = new URLSearchParams(location.search);
return (
<div>
{
// Do something depending on the id value
searchParams.get("id") // returns "12454812"
}
</div>
);
}
3.7 ) UNCONTROLLED COMPONENTS
❑ In most cases, we recommend using controlled components to implement forms. In a
controlled component, form data is handled by a React component. The alternative is
uncontrolled components, where form data is handled by the DOM itself.
❑ To write an uncontrolled component, instead of writing an event handler for every state
update, you can use a ref to get form values from the DOM.
❑ For example, this code accepts a single name in an uncontrolled component:

class NameForm extends React.Component

constructor(props)

super(props);

this.handleSubmit = this.handleSubmit.bind(this);

this.input = React.createRef();

}
handleSubmit(event)

alert('A name was submitted: ' + this.input.current.value); event.preventDefault();

render()

return

<form onSubmit={this.handleSubmit}>

<label> Name: <input type="text" ref={this.input} />

</label>

<input type="submit" value="Submit" />

</form> );

Since an uncontrolled component keeps the source of truth in the DOM, it is sometimes

easier to integrate React and non-React code when using uncontrolled components. It

can also be slightly less code if you want to be quick and dirty. Otherwise, you should

usually use controlled components.


❑ Uncontrolled components refer to components that manage their own state

internally. They use a ref to access the DOM element's current value and update the

state accordingly.

❑ A controlled functional component is a component that receives its current value and

update callback via props. For example, consider a simple form that accepts an email

address
const ControlledInput = (

{ value, onChange }) => (

<input value={value} onChange={(e) => onChange(e.target.value)} />

);

const LoginForm = () => {

const [email, setEmail] = useState("");

const [password, setPassword] = useState("");

return (

<form>

<ControlledInput value={email} onChange={setEmail} placeholder="Email" />

<ControlledInput

value={password}

onChange={setPassword}

placeholder="Password"

/>

<button>Submit</button>

</form>

);

};
❑ In this example, the ControlledInput component receives its current value and
an onChange callback via props. The LoginForm component maintains the state of
email and password, and when the user types into the inputs, it calls
the onChange callback and updates the state, which in turn updates the input values.
❑ An uncontrolled component in React is a component that does not store its form data
in its internal state. Instead, it lets the DOM handle the form data directly. Here is an
example:
import React, { useRef } from "react";

const UncontrolledInput = ({ placeholder }) => {


return <input defaultValue="" placeholder={placeholder} />;
};

const LoginForm = () => {


const emailRef = useRef();
const passwordRef = useRef();

const handleSubmit = (event) => {


event.preventDefault();

const email = emailRef.current.value;


const password = passwordRef.current.value;

console.log("Email:", email);
console.log("Password:", password);
};

return (
<form onSubmit={handleSubmit}>
<UncontrolledInput ref={emailRef} placeholder="Email" />
<UncontrolledInput ref={passwordRef} placeholder="Password" />
<button type="submit">Submit</button>
</form>
);
};
❑ In this example, UncontrolledInput using the useRef hook to create references
(emailRef and passwordRef) to the input fields. When the form is submitted, we can
access the values of the input fields directly through these refs.

❑ In real-world example, in a payment system, you would use a controlled component to


handle the form inputs where user enter the card information, so that the state of the
form data is managed by the parent component and it can be sent to the server for
processing. An uncontrolled component could be used for something like a search bar,
where the search results are displayed below the bar, and the state of the search bar is
managed internally by the component.

3.8 ) AUXILLARY COMPONENTS

Prior to React v16, returning multiple elements from a component required to wrap them in

an auxiliary element, e.g.

const Root = () => {

return <div>

<p>Hello, World!</p>

<p>I am a demo for react-aux.</p>

</div>;

};

The latter produces the following DOM:

<div>

<p>Hello, World!</p>

<p>I am a demo for react-aux.</p>

</div>
Starting with React v16, a single component can return multiple components without a

wrapping element, e.g.

const Aux = (props) => {

return props.children;

};

const Root = () => {

return <Aux>

<p>Hello, World!</p>

<p>I am a demo for react-aux.</p>

</Aux>;

};

The latter produces paragraph elements without the wrapping node:

<p>Hello, World!</p>

<p>I am a demo for react-aux.</p>

As you can see, react-aux is literally just 3 lines of code. Therefore, you could implement it

in your own codebase without using react-aux. However, props => props.children on its

own does not explain the intent. react-aux as an abstraction serves the purpose of enabling

a self-documenting code, i.e. the next time you see someone doing:

import Aux from 'react-aux';

const Root = () => {

return <Aux>

<p>Hello, World!</p>

<p>I am a demo for react-aux.</p>

</Aux>;

};
3.9 ) HOW TO PASS DATA FROM CHILD COMPONENT TO ITS PARENT IN

REACTJS ?

❑ In ReactJS, data flow between components is typically unidirectional, meaning

data is passed from parent components to child components. However, there are

scenarios where you may need to pass data from a child component back to its

parent component.

❑ Data can be passed from the parent to the child component via props. Any

properties of the parent component, be it variables or functions alike, can be

passed to the child component as props. While there is no direct way to pass data

from the child to the parent component, there are workarounds. The most

common one is to pass a handler function from the parent to the child component

that accepts an argument which is the data from the child component. This can

be better illustrated with an example.

Approach:

Following are the steps to pass data from the child component to the parent

component:

➢ In the parent component, create a callback function. This callback function will

retrieve the data from the child component.

➢ Pass the callback function to the child as a props from the parent component.

➢ The child component calls the parent callback function using props and passes the

data to the parent component.


import React from "react";
export default function App() {
return (
<div> <Parent /> </div>
);}
Consider a simple application with the App component shown above. It returns
a Parent component within a div element. Let’s look the Parent and Child components.
const Parent = () => {
const [message, setMessage] = React.useState("Hello World"); const chooseMessage =
(message) => {
setMessage(message);
}; return (
<div>
<h1>{message}</h1>
<Child chooseMessage={chooseMessage} />
</div>
);};const Child = ({ chooseMessage }) => {
let msg = 'Goodbye';
return (
<div>
<button onClick={() => chooseMessage(msg)}>Change Message</button>
</div>
);};

The initial state of the message variable in the Parent component is set to ‘Hello World’ and
it is displayed within the h1 tags in the Parent component as shown. We write
a chooseMessage function in the Parent component and pass this function as a prop to
the Child component. This function takes an argument message. But data for
this message argument is passed from within the Child component as shown. So, on click of
the Change Message button, msg = ‘Goodbye’ will now be passed to
the chooseMessage handler function in the Parent component and the new value
of message in the Parent component will now be ‘Goodbye’.
This way, data from the child component(data in the variable msg in
Child component) is passed to the parent component.
10. ASSIGNMENT – 1 To 5
Assignment I : (CO3,CO4,K2)
1. What is the difference between Class Components and Functional Components in
React? Provide examples.
2. Explain the role of props in React. Are they mutable or immutable? How do they
flow between components?
3. Write a simple React functional component that uses useState to toggle a boolean
value.
4. What are controlled and uncontrolled components in React? Explain with examples.
5. What is PropTypes in React? How does it help in maintaining type safety? Provide an
example.

Assignment II: (CO3,CO4,CO5,K2)


1. Explain the React Class Component lifecycle methods - componentDidMount,
shouldComponentUpdate, and componentDidCatch.
2. Create a React component using useRef to focus an input field when a button is
clicked.
3. Implement a simple React Router setup with two pages (Home and About).
4. Show how to use useEffect to fetch and display data when a component mounts.
5. Demonstrate how to pass data from a parent component to a child component
using props.

Assignment III: (CO3,CO4,CO5,K3)


1. Implement a React component that maintains a list of customers using a JavaScript
Map collection.
2. Provide add, delete, and update functionalities.Use useHistory (or useNavigate in
React Router v6) to navigate between pages in a React app.
3. Demonstrate how to handle form inputs using controlled components in React.
4. Create a React component that conditionally renders UI based on a boolean state
variable.
5. Implement a simple child-to-parent communication using callback functions.
10. ASSIGNMENT – 1 To 5
Assignment IV : (CO3,CO4,CO5,K4)
1. Build a login page using React and implement routing to navigate between a
dashboard and an admin page.
2. Implement a protected route in React that only allows access to authenticated
users.
3. Use React Context API to manage global state and provide it to multiple
components.
4. Develop a React component that utilizes useEffect to update the document title
dynamically based on state changes.
5. Implement an uncontrolled form component that collects user data and logs it to
the console on submission.

Assignment V: (CO3,CO4,CO5,K5)
1. Develop a full-fledged React application that includes a Login Page, Dashboard, and
Admin Page with authentication using protected routes.
2. Implement a customer management system using WeakMap and Map collections in
JavaScript.
3. Demonstrate the differences and benefits of each.Create a React application that
integrates with an external API, fetches data, and displays it using a paginated list.
4. Build a component that allows users to enter form data using controlled
components, validates inputs, and displays error messages dynamically.
5. Implement a complex parent-child interaction system where a parent component
provides state updates to multiple child components and receives updates from
them..
11. PART-A : QUESTIONS AND ANSWERS

1. What is Components in React (CO3,K2)

A Component is one of the core building blocks of React. In other words, we can say that
every application you will develop in React will be made up of pieces called components.
Components make the task of building UIs much easier. You can see a UI broken down
into multiple individual pieces called components and work on them independently and
merge them all in a parent component which will be the final UI.

2. What are types Of Components in Reactjs (CO3,K2)

Components in React basically return a piece of JSX code that tells what should be
rendered on the screen.
Types of components in ReactJS
In React, we mainly have two types of components:
1. Class Based Component
2. Function Based Component

3. Define functional based components (CO3,K2)


Functional components are simply javascript functions. We can create a functional
component in React by writing a javascript function. These functions may or may not
receive data as parameters,
The below example shows a valid functional component in React:

function demoComponent() {

return (<h1>

Welcome Message!

</h1>);

}
11. PART-A : QUESTIONS AND ANSWERS

3. What is class based components ?(CO3,K2)


The class components are a little more complex than the functional components. The
functional components are not aware of the other components in your program whereas
the class components can work with each other. We can pass data from one class
component to another class component. We can use JavaScript ES6 classes to create
class-based components in React. The below example shows a valid class-based
component in React:
class Democomponent extends React.Component {
render() {
return <h1>Welcome Message!</h1>;
}
}
4. How to "Render a Components in ReactJS” ? (CO4,K3)

React is also capable of rendering user-defined components. To render a component in


React we can initialize an element with a user-defined component and pass this element
as the first parameter to ReactDOM.render() or directly pass the component as the first
argument to the ReactDOM.render() method.
The below syntax shows how to initialize a component to an element:
const elementName = <ComponentName />;
In the above syntax, the ComponentName is the name of the user-defined component.
Note: The name of a component should always start with a capital letter. This is done to
differentiate a component tag from HTML tags.
The below example renders a component named Welcome to the Screen:
Open your index.js file from the project directory, to see the changes in index.js.

5. Give example for how to "Render a Components in ReactJS”. (CO3,K2)


import React from 'react';
import ReactDOM from 'react-dom';
// This is a functional component
const Welcome = () => {
return <h1>Hello World!</h1>
}
ReactDOM.render(
<Welcome />,
document.getElementById("root")
);

6. What is Composing Components ? (CO4,K2)


Components can refer to other components in their output. This lets us use the same
component abstraction for any level of detail. A button, a form, a dialog, a screen: in
React apps, all those are commonly expressed as components.
For example, we can create an App component that renders Welcome many times:
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
function App() {
return ( <div>
<Welcome name="Sara" /> <Welcome name="Cahal" /> <Welcome name="Edite" />
</div> ); }

7. Define Extracting Components (CO4,K2)


function Comment(props) {
return (
<div className="Comment">
<div className="UserInfo">
<img className="Avatar" src={props.author.avatarUrl} alt={props.author.name} />
<div className="UserInfo-name"> {props.author.name} </div>
</div>
<div className="Comment-text"> {props.text} </div>
<div className="Comment-date"> {formatDate(props.date)} </div>
</div> ); }
8. Define with example how to extract the components. (CO3,K2)

import React, { Component } from 'react';


class App extends React.Component {
constructor() {
super();
this.state = {
data:
[
{
"name":“RMKEC"
},
{
"name":“RMDEC"
},
{
"name":“RMKCET"
}
]
}
}
render() {
return (
<div>
<StudentName/>
<ul>
{this.state.data.map((item) => <List data = {item} />)}
</ul>
</div>
);
}
}
class StudentName extends React.Component {
render() {
return (
<div>
<h1>COLLEGE DETAILS</h1>
</div>
);
}
}
class List extends React.Component {
render() {
return (
<ul>
<li>{this.props.data.name}</li>
</ul>
);
}
}
export default App;
9. Define React State (CO3,K2)

❑ The state is an updatable structure that is used to contain data or information about the
component. The state in a component can change over time. The change in state over
time can happen as a response to user action or system event. A component with the
state is known as stateful components. It is the heart of the react component which
determines the behavior of the component and how it will render. They are also
responsible for making a component dynamic and interactive.
❑ A state must be kept as simple as possible. It can be set by using the setState() method
and calling setState() method triggers UI updates. A state represents the component's
local state or information. It can only be accessed or modified inside the component or
by the component directly. To set an initial state before any interaction occurs, we need
to use the getInitialState() method.
❑ For example, if we have five components that need data or information from the state,
then we need to create one container component that will keep the
state for all of them.
10 . Mention State in React (CO4,K2)

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.
import React, { Component } from 'react';
class App extends React.Component {
constructor() {
super();
this.state = { displayBio: true };
}
render() {
const bio = this.state.displayBio ? (
<div>
<p><h3> 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.</h3></p>

</div>
) : null;
return (
<div>
<h1> Welcome to REACT CLASS</h1>
{ bio }
</div>
);
}
}
export default App;
11. How do you change the state in react? ( CO3,K2)

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.
this.toggleDisplayBio = this.toggleDisplayBio.bind(this);

NOTE: (Refer the DCM above for example)

12. Define the lifecycle states with the diagram. ( CO3,K2)


13. What is Mounting , constructor and render in the react life cycle component?
(CO4,K2)
This phase of the component lifecycle is used to call the method when the instance of the
component can be created. It is also called while inserting the component into the HTML
DOM. There are a few methods used in the mounting phase.
constructor()
The constructor() method is called before anything else when the component is initiated, and
it is the natural place to set up the initial state and other initial values. This method is called
with the props as arguments, and you should always start by calling the super (props) before
anything else, this will initiate the parent’s constructor method and allows the component to
inherit methods from its parent (React.Component).
render()
Rendering is a crucial procedure programmer must manage in front end development. The
render() method is the only required method in a class component and is responsible for
describing the view to be rendered to the browser window. It is important to note that this
method is not user callable but is a part of the React Component Lifecycle. Within the
lifecycle, there are a number of scenarios when render is called;
After the React component is first instantiated, following the constructor() call.
After an update to the component’s props
After a setState() call

14. Mention the key points of componentDidMount() and Updating() (CO4,K2)

The componentDidMount() method enables us to execute the React code when the
component is already placed in the Document Object Model. All the AJAX requests and the
DOM or state updation should be coded in the componentDidMount() method block. After all
the elements of the page are rendered correctly, this method is called. After the markup is set
on the page, this technique is called by React itself to either fetch the data from an External
API or perform some unique operations which need the JSX elements.
Updating
This phase of the component lifecycle is triggered as soon as any changes are found in terms
of state or props that allow the DOM to be re-rendered again and again to update the DOM
elements. The updating phase includes several lifecycle hooks; requests.
15. Define the below: (CO4,K2)
getDerivedStateFromProps
This method is invoked right before calling the render method, both on the initial mount and
on subsequent updates. It should return an object to update the state, or null to update
nothing. The method exists for rare use cases where the state depends on changes in props
over time.
shouldComponentUpdate ()
The shouldComponentUpdate () method may be used to let React know if a component’s
output is not affected by the current change in state or props. The default behaviour is to re-
render on every state change, and in the vast majority of cases, you should rely on the
default behaviour.
componentDidUpdate ()
The componentDidUpdate method is called after the component is updated in the DOM. The
componentDidUpdate lifecycle method is invoked after the getSnapshotBeforeUpdate. As with
the getSnapshotBeforeUpdate method, it receives the previous props and state as arguments.
Whatever value is returned from the getSnapshotBeforeUpdate lifecycle method is passed as
the third argument to the componentDidUpdate method. nnecessary network

16. Define the following: (CO4,K2)


Unmounting
The unmounting phase begins when an existing component is removed from the DOM. It
includes a single and important lifecycle hook, componentWillUnmount().
Error Handling
This is one of the most crucial phases of the component, error handling is used to trigger an
action in case of an error during the component rendering. There are two methods used to
manage the errors in the existing component.
17. What is ComponentDidCatch() (CO4,K2)
ComponentDidCatch() was added in React 16 and is used in error boundaries. A component
becomes an error boundary if it defines the componentDidCatch method. In this method,
this.set State can be called and used to catch an unhandled Javascript error in a child
component tree and display a fallback UI instead of the component that crashed. These errors
are caught during rendering, in lifecycle methods, and in constructors of the whole tree below
them.
18. How to Use ComponentDidUpdate() (CO3,K2)
❑ This lifecycle method gets called right after a change in props or a state change has
occurred. This might happen if new props have been provided by a parent component or
an internal state has been changed.
❑ The componentDidUpdate gets called after a render which means that you can access DOM
nodes in it. This function receives props and states as parameters. It can also access new
props and state with this.props and this.state. It provides the previous pros and state
values and in this way it allows you to do a comparison of a before and current snapshot.
❑ Best use-cases of the ComponentDidUpdate() lifecycle;
✓ API calls after specific conditions have been met
✓ DOM manipulation after the component has been rendered.
✓ Update React state or stores like Redux and Mobx after a set of conditions have been met.

19. Mention the React States (CO3,K2)


Consider the ticking clock example from one of the previous sections. In Rendering Elements,
we have only learned one way to update the UI. We call root.render() to change the rendered
output:
const root = ReactDOM.createRoot(document.getElementById('root'));
function tick() {
const element = (
<div> <h1>Hello, world!</h1>
<h2>It is {new Date().toLocaleTimeString()}.</h2>
</div> );
root.render(element);
}
setInterval(tick, 1000);
20 . What is REACTJS HOOKS? (CO5,K2)
Hooks are a new addition in React 16.8. They let you use state and other React features
without writing a class.
import React, { useState } from 'react';
function Example() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);
return (
<div> <p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}> Click me </button>
</div> );
}
Before we continue, note that Hooks are:
• Completely opt-in. You can try Hooks in a few components without rewriting any
existing code. But you don’t have to learn or use Hooks right now if you don’t want to.
• 100% backwards-compatible. Hooks don’t contain any breaking changes.
• Available now. Hooks are now available with the release of v16.8.0.
• There are no plans to remove classes from React. You can read more about the gradual
adoption strategy for Hooks in the bottom section of this page.
• Hooks don’t replace your knowledge of React concepts. Instead, Hooks provide a more
direct API to the React concepts you already know: props, state, context, refs, and
lifecycle.
21. What is UseState HOOKS ?(CO5,K2)
Voting.js
import { useState } from "react";
export function Voting(props) {
const [like, setLike] = useState(0);
const [dislike, setDislike]=useState(0);
return (
<div className="Votes"
style = {like>dislike?{background:"green"}:{background:"yellow"}}>
<h1>{props.brandname}</h1>
<h4>{props.Model}</h4>

<button onClick={() => setLike(like + 1)}> {like}</button>


<button onClick={() => setDislike(dislike + 1)}> {dislike}</button>
</div>
);
}
22. Define UseEffect HOOKS (CO5,K2)

The Effect Hook, useEffect, adds the ability to perform side effects from a function
component. It serves the same purpose as componentDidMount, componentDidUpdate,
and componentWillUnmount in React classes, but unified into a single API. (We’ll show
examples comparing useEffect to these methods in Using the Effect Hook.)
For example, this component sets the document title after React updates the DOM:

import React, { useState, useEffect } from 'react';


function Example() {
const [count, setCount] = useState(0);
// Similar to componentDidMount and componentDidUpdate:
useEffect(() => {
// Update the document title using the browser API
document.title = `You clicked ${count} times`; });
return (
<div> <p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}

23. List out the Rules of Hooks (CO5,K2)

❑ Hooks are JavaScript functions, but they impose two additional rules:
❑ Only call Hooks at the top level. Don’t call Hooks inside loops, conditions, or nested
functions.
❑ Only call Hooks from React function components. Don’t call Hooks from regular
JavaScript functions.
24. List out the Difference between Controlled and Uncontrolled Components
(CO3,K2)

25. What are React-Router HOOKS?. (CO3,K2)


React-Router is a popular React library that is heavily used for client-side routing and offers
single-page routing. It provides various Component APIs( like Route, Link, Switch, etc.) that
you can use in your React application to render different components based on the URL
pathnames in a single page.
Hooks Of React Router 5: React Router 5 offers 4 hooks that you can use in your react
applications:
✓ useHistory
✓ useParams
✓ useLocation
✓ useRouteMatch
26. Mention about useHistory: (CO3,K2)

This is one of the most popular hooks provided by React Router. It lets you access the history
instance used by React Router. Using the history instance you can redirect users to another
page. The history instance created by React Router uses a Stack( called “History Stack” ), that
stores all the entries the user has visited.
Syntax :

import { useHistory } from "react-router-dom"; // Inside a functional component export

default function SomeComponent(props){ // The useHistory() hook returns the history //

object used by React Router const history = useHistory(); }


27.Mention about useLocation:(CO3,K2)
This hook returns the location object used by the react-router. This object represents the
current URL and is immutable. Whenever the URL changes, the useLocation() hook returns a
newly updated location object. Some of its use includes extracting the query parameters from
the URL and doing something depending on the query parameters. The “search” property of
the location object returns a string containing the query part of the URL.
Syntax :
import { useLocation } from "react-router-dom";
// Inside functional component export default function SomeComponent(props)
{
const location = useLocation();
}
28.Write about Project Structure in Reactjs using React-router: (CO3,K2)
29. Write about useParams: (CO3,K2)

This hook returns an object that consists of all the parameters in URL.

import { useParams } from "react-router-dom"; // Inside a functional component export

default function SomeComponent(props){

const params = useParams(); }

These URL parameters are defined in the Route URL. For example,

<Route path="/profile/:userName" component={Profile} />The colon(“:”) after

“/profile/” specifies that “userName” is actually a variable or parameter that is dynamic.

For example, in the url “/profile/johndoe”, “johndoe” is the value of the parameter

“userName”. So, in this case, the object returned by useParams() is:

{ userName: "johndoe" }

30. Write about useLocation: (CO3,K2)


This hook returns the location object used by the react-router. This object represents
the current URL and is immutable. Whenever the URL changes, the useLocation() hook
returns a newly updated location object. Some of its use includes extracting the query
parameters from the URL and doing something depending on the query parameters.
The “search” property of the location object returns a string containing the query part
of the URL.
Syntax :
import { useLocation } from "react-router-dom";
// Inside functional component export default function SomeComponent(props)
{
const location = useLocation();
}
12. PART B : QUESTIONS
Q. CO
Questions K Level
No. Level

Describe the Key Point of Class components


1 CO3 K3
lifecycle of Reactjs .

2 Explain UseHistory, UseReducer, UseCallback CO3 K3

3 Explain UseLocation, UseReducer, UseRef CO3 K4

Describe in detail about the REACT ROUTER


4 CO5 K2
HOOKS

5 Explain in detail UseState HOOKS . CO5 K3

6 Explain in detail UseEffect HOOKS . CO5 K4

Explain detail about Controlled And


7 CO4 K3
Uncontrolled Components

What is a REST API?


8 CO2 K4
How to Consume APIs Using The Fetch API

Develop an Student Portfolio application


9 CO4 K3
using Hooks in ReactJS.
An e-commerce website built using React,
where we can filter clothes products using
their customer preferred sizes as M, L or XL
10 etc. We have a button called “Add to cart” CO4 K3
below each product shown on the web page,
once user selects any product, it will go to
cart. At the end it can be used to checkout.
13. SUPPORTIVE ONLINE CERTIFICATION COURSES

• React Basics - coursera

https://www.coursera.org/learn/react-basics

• Udemy: "React - The Complete Guide (incl


Hooks, React Router, Redux)" by Maximilian
Schwarzmüller:

https://www.udemy.com/course/react-the-complete-
guide-incl-redux/learn/

• Edx: "CS50’s Web Programming with Python


and JavaScript" by Harvard University:

https://cs50.harvard.edu/web/2020/

75
14. REAL TIME APPLICATIONS

1) A WEB APPLICATION PROVIDING RANGE OF OPTIONS TO CAR BUYERS


Car selling website is where the customer can buy and sell their car. This website is
user friendly and ease to use for any customer, it has effective search box to get the
precise and suitable car for the user. A rich search facility is always there from where
customer can search vehicle via category, keywords, price range, brand, types, fuel
types, etc. The website displays information of the customer support person on the
homepage so that user can directly contact them or meet them which help in
decreasing the communication gap. This website also provides a facility for road side
assistance. The social media plugin will help the company to know their popularity
over the social media.

2) PLAY YOUR FANTASY SPORTS ONLINE USING WEB APPLICATION


This application is developed for users who are interested in playing fantasy sports
online. Users can play fantasy sports with close friends or people you met over the
internet. Users can create their own leagues and can invite friends to play in their
league or they can play in others leagues. Users can easily change the league size,
payment deadlines, payout verifications and payout timelines. This system guarantee
the professional safekeeping of the funds through full-featured security measures.
User can withdraw funds from their account. User can refer a friend to play a
particular league.

3) BOOTSTRAP & RESPONSIVE DESIGN


Responsive web design is a way of making a single website that works effectively on
both desktop browsers and the myriad of mobile devices on the market. It involves
having a website that enhances the viewing experience, irrespective of which device
is being used. Bootstrap makes the front-end web development faster and easier. It is
made for the users of all skill levels, devices of all shapes and projects of all sizes. It is
considered the most popular HTML, CSS, and JavaScript framework for developing
responsive & mobile-first websites. With a responsive website design, you don't have
to have worry about having different websites for various devices or making sure that
your website runs properly on a mobile device.
14. REAL TIME APPLICATIONS

At Spaculus, we can incorporate your new website design or we modify it and make it
responsive if you already own a website. Our team of experts uses various tools and
technologies to make your website more accessible such as media queries, flexible
grid based layouts that use re-sizing and flexible images & media.

4) Navigating the Internet


HTML is an essential element in navigating between web pages. Navigation is possible
using the hypertext concept. The linking is also simpler. From the internet user’s point
of view, they click on a text which takes them to the next page. HTML facilitates
navigation by hyperlinking with the help of an anchor tag.
<a href="geeksforgeeks.org"> Click here to open! </a>Navigation can increase
visitors to a website. It increases user activity on the website. It also helps the web
user to look at the content structure and organization.

5)Storage Function in the Browser


Storage of data in the browser was tedious in the past. For a user to save the data of
the browser that persists between two sessions, the user’s cookies or infrastructure is
to be built from the server end. This process has now been eased with
HTML5. HTML5 has roped in new features. Such storage features are localStorage
and IndexDB.
The web storage objects window.localStorage and window.sessionStorage store data
with no expiration date and storage for one session respectively. The localStorage
object will have the data saved even when the browser is closed. setItem and
removeItem are the functions commonly used to store and remove data from the
storage. Also, the most important part is that these features are supported by all
browsers.

To Store – localStorage.setItem(“username”, “Nisha”);


To Retrieve – document.getElementById(“result”).innerHTML =
localStorage.getItem(“username”);
To Remove – localStorage.removeItem(“username”);
15. CONTENT BEYOND SYLLABUS
Auxiliary Components in React:
Introduction to Auxiliary Components:
In React development, managing layout structures and reusable wrappers is a crucial
aspect of writing clean and maintainable code. Auxiliary Components (Aux
Components) provide a lightweight way to wrap child components without adding
extra HTML elements to the DOM.
Why Use Auxiliary Components?
By default, React requires components to return a single parent element. However, in
many cases, we need to wrap multiple elements without affecting the rendered
structure. Using an extra <div> for wrapping can sometimes cause unwanted layout
issues and additional nesting. Auxiliary Components solve this by returning multiple
child elements without adding an unnecessary wrapper element.
Implementation of an Auxiliary Component:
An Auxiliary Component is typically implemented as a higher-order component (HOC)
or as a functional component that returns children directly.
Example 1:
Using a Simple Auxiliary Component:
jsx
const Aux = (props) => props.children;
export default Aux;
Usage in a Parent Component:
jsx
import React from 'react';
import Aux from './Aux';
const Layout = () => {
return (
<Aux>
<header>Header Section</header>
<main>Main Content</main>
<footer>Footer Section</footer>
</Aux> ); };
78
export default Layout;
15. CONTENT BEYOND SYLLABUS
Here, the <Aux> component does not add any extra <div>, keeping the DOM clean
while grouping multiple elements logically.
Alternative Approach: React Fragments
React provides a built-in alternative to Auxiliary Components: Fragments
(<React.Fragment>).

jsx
import React from 'react';

const Layout = () => {


return (
<React.Fragment>
<header>Header Section</header>
<main>Main Content</main>
<footer>Footer Section</footer>
</React.Fragment>
);
};
export default Layout;
or using shorthand syntax:
<>
<header>Header Section</header>
<main>Main Content</main>
<footer>Footer Section</footer>
</>
Key Benefits of Auxiliary Components

Avoids Unnecessary HTML Elements – Helps maintain clean DOM structure.

Improves Readability – Simplifies component composition.

Enhances Reusability – Can be used in multiple components to manage layout.

79
16. ASSESSMENT SCHEDULE

• Tentative schedule for the Assessment During


2024-2025 Even Semester

Name of the
S.NO Start Date End Date Portion
Assessment
As per schedule after
1 Unit Test 1 UNIT 1
Unit I completion
2 IAT 1 28.01.2025 03.02.2025 UNIT 1 & 2

As per schedule after


3 Unit Test 2 UNIT 3
Unit III completion

4 IAT 2 10.03.2025 15.03.2025 UNIT 3 & 4

5 Model 03.04.2025 17.04.2025 ALL 5 UNITS

163

80
17. PRESCRIBED TEXT BOOKS
&
REFERENCE BOOKS
TEXT BOOKS:

JAVASCRIPT THE DEFINITIVE GUIDE 7/ED Paperback – 15 June 2020

Full-Stack React, TypeScript, and Node: Build cloud-ready web applications using React 17
with Hooks and GraphQL Paperback – Import, 18 December 2020

Advanced Web Development with React Paperback – 1 January 2020

REFERENCES:

PARENTAL WEBSITE - https://reactjs.org/

The Road to Learn React: Your journey to master plain yet pragmatic React.js by Robin
Wieruch

Learning React: Functional Web Development with React and Redux by Alex Banks and Eve
Porcello

Learning React by Kirupa Chinnathambi

"React Up & Running" by Stoyan Stefanov

https://www.edureka.co/reactjs-redux-certification-training

ONLINE LEARNING PLATFORMS :

CodePen,

CodeSandbox (ß Preferred)

Stackblitz.
18. MINI PROJECT SUGGESTION

1) HOW TO CREATE A COUNTER (CO3,K3)

By manipulating the DOM, you have infinite possibilities. You can create applications that
update the data of the page without needing a refresh. Also, you can create applications
that are customizable by the user and then change the layout of the page without a
refresh.
2) JAVASCRIPT CLOCK (CO3,K3)
Key concepts covered:
Variables
Conditional logic
Program flow
Functions
3)To-Do List (CO3,K3)
Why do this project?
You’ll beef up your skills at coding interactive lists, which lets users add, remove, and group
items
You can use this beginner JavaScript project in your daily life and add it to your portfolio
Learn more about how to use arrays, nested functions, and local storage API
4) Tic_Tac-Toe (CO4,K3)
Implement the JavaScript code so that the player can set difficulty level as easy or hard,
choose whether to play as X or O, play a game with the computer, have it remember who
won or drew, and play again.

5) Guess the Word (CO4,K3)


Implement the JavaScript code so that players start by entering a letter. If they guess
correctly, the letter appears in the word. If they guess incorrectly, they learn how many
guesses they have remaining. The player can also see which letters they’ve already
guessed. The game lets the player know if they’ve already guessed a letter or entered a
non-alphabetic character!
Thank you

Disclaimer:

This document is confidential and intended solely for the educational purpose of RMK Group of
Educational Institutions. If you have received this document through email in error, please notify the
system manager. This document contains proprietary information and is intended only to the
respective group / learning community as intended. If you are not the addressee you should not
disseminate, distribute or copy through e-mail. Please notify the sender immediately by e-mail if you
have received this document by mistake and delete this document from your system. If you are not
the intended recipient you are notified that disclosing, copying, distributing or taking any action in
relianceon the contents of this information is strictly prohibited.

You might also like