0% found this document useful (0 votes)
3 views139 pages

Complete Notes

The document provides comprehensive notes on React JS, covering versions up to 19x, installation of necessary libraries, and component structure. It outlines the rules for creating components, including syntax, JSX usage, and integration of Bootstrap for styling. Additionally, it discusses the concept of modules in JavaScript and the structure of a React application using Vite as a bundler.

Uploaded by

aditikuhar627
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)
3 views139 pages

Complete Notes

The document provides comprehensive notes on React JS, covering versions up to 19x, installation of necessary libraries, and component structure. It outlines the rules for creating components, including syntax, JSX usage, and integration of Bootstrap for styling. Additionally, it discusses the concept of modules in JavaScript and the structure of a React application using Vite as a bundler.

Uploaded by

aditikuhar627
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

React JS — 6PM Batch Notes

26 December 2025

1. Upto React 17x version


[Link]("Markup | Component",
[Link]("root")
)

2. React 18x & 19x version


const root = [Link]([Link]("root"));
[Link]("Markup | Component");

Download and Install Library required for project:

1. Run the following commands in terminal


> npm install react@18 --save
> npm install react-dom@18 --save
> npm install @babel/standalone --save
(or)
> npm i react@18 react-dom@18 @babel/standalone --save

2. All library files are copied into "node_modules" folder

3. Link the following files to your HTML page


<script src="../node_modules/react/umd/[Link]"> </script>
<script src="../node_modules/react-dom/umd/[Link]">
</script>
<script src="../node_modules/@babel/standalone/[Link]"> </script>

4. Your custom script is defined in <script> block with type as


a) text/babel (or)
b) text/jsx
Syntax:
<script type="text/babel">
</script>

React Components
- Component comprises 3 elements
a) Design
b) Styles
c) Logic
- Design is defined using HTML.
- Styles are defined with CSS.
- Logic is defined with JSX or TSX.
- Technically component is a Javascript
a) Class
b) Function
- Classes are supported in React but not recommended in modern code.
- React 19x version always recommends to design component with function.

Component Rules:
- A component must be a Javascript.
- You can create using declaration or expression.
- Name must start with uppercase letter.
Syntax: Declaration
function Login()
{
}
Syntax: Expression
const Login = function() {
}
- Component function can't be void type.
- A component function must return a JSX element.
function Login()
{
return (
<div>
JSX element
</div>
)
}
- Component function can return only one fragment.
return(
<h1> Welcome </h1> => invalid
<p> React JS </p>
)
return(
<header> => valid
<h1> </h1>
<p> </p>
</header>
- Every JSX element must have end token.
<img> => invalid
<img> </img>
<img />
<input> => invalid
<input />
<input> </input>
<br />
- Every JSX element can use only properties not attributes.
<img class="attribute"> => invalid
[Link]("img").className;
<img className="some" />
Ex:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Demo</title>
<style>
nav {
display: flex;
justify-content: space-between;
font-family: Arial;
padding: 20px;
font-size: 20px;
border:1px solid gray;
background-color: black;
color:white;
}
nav span {
margin-right: 20px;
}
</style>
<script src="../node_modules/react/umd/[Link]"></script>
<script src="../node_modules/react-dom/umd/[Link]"></script>
<script src="../node_modules/@babel/standalone/[Link]"></script>
<script type="text/babel">

function Navbar(){
return(
<nav>
<div className="brand-title">Shopping.</div>
<div>
<span> Home </span>
<span> Shop </span>
<span> Pages </span>
<span> Offers </span>
<span> Contact </span>
</div>
<button>Signin </button>
</nav>
)
}
function NewUser(){
return(
<div>
<a href="#">New User? Register</a>
</div>
)
}

function Login(){
return(
<form>
<h3>User Login</h3>
<dl>
<dt> User Name </dt>
<dd> <input type="text" /> </dd>
<dt>Password</dt>
<dd><input type="password" /></dd>
<dt>Email</dt>
<dd><input type="email" /></dd>
</dl>
<button>Login </button>
<NewUser />
</form>
)
}
const root = [Link]([Link]("root"));
[Link](
<section>
<Navbar />
<Login/>

</section>
);
</script>
</head>
<body>
<noscript> Please enable JavaScript on your browser.</noscript>

<div id="root"></div>
</body>
</html>

27 December 2025

- Install libraries
- Components

Setup Bootstrap for project:


1. Install following libraries into project
> npm install bootstrap bootstrap-icons --save
2. Link the following files to HTML page
<link rel="stylesheet" href="../node_modules/bootstrap/dist/css/[Link]">
<link re="stylesheet" href="../node_modules/bootstrap-icons/font/bootstrap-
[Link]">
<script src="../node_modules/bootstrap/dist/js/[Link]">
Ex:
[Link]

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Netflix</title>
<!-- Custom Style -->
<style>
body {
background-image: url("[Link]");
background-size: cover;
}
.shade {
background-color: rgba(0,0,0,0.6);
height: 100vh;
}
main {
padding-top: 100px;
}
</style>

<!-- Bootstrap Library -->


<link rel="stylesheet" href="../node_modules/bootstrap-icons/font/[Link]">
<link rel="stylesheet" href="../node_modules/bootstrap/dist/css/[Link]">
<script src="../node_modules/bootstrap/dist/js/[Link]"></script>

<!-- React Library -->


<script src="../node_modules/react/umd/[Link]"></script>
<script src="../node_modules/react-dom/umd/[Link]"></script>
<script src="../node_modules/@babel/standalone/[Link]"></script>
<script type="text/babel">

function NetflixHeader(){
return(
<header className="d-flex justify-content-between p-4 text-white">
<div className="fs-1 fw-bold text-danger">NETFLIX</div>
<div className="d-flex flex-row align-items-center">

<div className="input-group">
<span className="bi input-group-text bi-translate"></span>
<select className="form-select">
<option>Language</option>
</select>

</div>
<button className="btn mx-3 btn-danger">SignIn</button>

</div>
</header>
)
}

function NetflixMain(){
return(
<main className="text-center text-white">
<div className="fs-1 fw-bold">Unlimited movies, shows <br /> and more</div>
<div className="fs-5 mt-3">Starts at ■ 149. Cancel at any time.</div>
<div className="d-flex justify-content-center">
<NetflixRegister />

</div>

</main>
)
}

function NetflixRegister(){
return(
<form className="mt-4">
<div className="my-3">
Ready to watch? Enter your email to create or restart your membership.
</div>
<div className="d-flex align-items-center justify-content-center">
<div>
<div className="input-group input-group-lg">
<input type="email" placeholder="Your email address" className="form-control" />
<button className="btn mx-3 btn-danger"> Get Started <span className="bi bi-chevr
</div>
</div>
</div>

</form>
)
}

function NetflixIndex(){
return(
<div className="shade">
<NetflixHeader />
<NetflixMain />
</div>
)
}

const root = [Link]([Link]("root"));


[Link](<NetflixIndex />);

</script>
</head>
<body>
<noscript>Please enable Javascript on your browser.</noscript>
<div id="root"></div>
</body>
</html>

React 19 App

29 December 2025

FAQ: What are bundlers?


- It is a software tool used by developers to build application and
setup environment according to project requirements.
- There are various bundling tools like
a) Webpack
b) Parcel
c) Vite etc.
- Bundlers use a scaffolding technique.
- Scaffolding is the process of generating files and folders according to
the developers requirements.
- Ruby on Rails introduced "Scaffolding".

Create a new React App using Vite Bundler:

1. Open any location from terminal / command prompt

2. Run the following command


> npm create vite@latest app-name

Select Framework : React

Select Variant : Javascript

Experimental Rollout: No

Install Dependencies: Yes

Note: Project starts automatically after installing, you can terminate using
"Ctrl + C"

3. Open project folder in VS Code


React Application File Structure:

File / Folder Description

node_modules It comprises of all files related to dependencies.

public It comprises of static resources like, images, docs.

src It comprises of dynamic resources like: css, scss, ts, js etc.

.gitignore It configures the files to ignore while publishing on


to GIT.

[Link] It is Javascript language analysis tool.


It sets rules for Javascript in current project.

[Link] It comprises of project meta data.


It defines dependencies and their versions.
Developer can change the versions in design.

[Link] It is used for production. It can't be modified.

[Link] It is a help document by developers for developers.

[Link] It is bundler configuration file. You can plugin


external frameworks and libraries to project.

[Link] It is startup page.

4. Run following command from terminal to start project


> npm run dev
[Link]

React Application Flow [High Level]

1. Client request react application from browser


[Link]

2. Browser loads [Link] using DOMContentLoaded event

3. [Link] loads Static DOM into browser.

4. It loads all dependencies from "[Link]"

5. It creates a virtual DOM by using createRoot()

6. It renders App component into virtual DOM.


[Link]
7. App component is updated into actual DOM.

8. Static DOM is transformed into Dynamic DOM.

Note: The process of converting static DOM into dynamic DOM is


known as "Bootstrapping".

30 December 2025

- Module refers to a portion of code.


- Modular refers to part-by-part.
- It allows to use only the required code for application.
- It makes the application light weight and faster.
- Technically every Javascript file is considered as a module.
[Link] => home module
[Link] => index module
- A module in Javascript comprises of
a) Variables
b) Functions
c) Classes
- Module members are not accessible outside the module scope.
- You have to mark them as "export" in order to import and use in any location.
export var title = "Welcome";
export function name() { }
export class Name { }
- Importing a member from module depends on module system.
- Javascript have various module systems like
a) Common JS
b) ESModule
c) UMD (Universal Module Distribution)
d) AMD (Asynchronous Module Distribution)
- Javascript inside browser uses "ESModule".
// ESModule, UMD, AMD
import { varName, funName, className } from "[Link]";
// Common JS
const refName = require("[Link]");
[Link]
[Link]
- You have to export a member while declaring.
- If you want to export after declaration, then it must a

default export.
var title = "Welcome";
export default title;
- Every module can have only one default export.
- You can import default export outside the import block.
import { title } from "[Link]"; // invalid if title is default
import title from "[Link]"; // valid for default members
- You can import default members with others, but make sure that default is
the first import.
import { others } , title from "[Link]"; // invalid
import title, { others } from "[Link]"; // valid
- If you want to import all members from a module then you have to use
aliasing method.
import * as aliasName from "[Link]";
[Link];
[Link];
[Link];
- You can import members from multiple modules.
- If different modules have same name members then it leads to ambiguity.
- You can handle ambiguity issues by aliasing.
import { title as homeTitle } from "[Link]";
import { title as loginTitle } from "[Link]";
Ex:
[Link]

export function title(){


return "Home Page";
}

[Link]

export function title(){


return "Login Page";
}

[Link]

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script type="module">
import { title as homeTitle } from "./[Link]";
import { title as loginTitle } from "./[Link]";

[Link]("h1").textContent = loginTitle();
</script>
</head>
<body>
<h1></h1>

</body>
</html>

Note: Clean up "[Link]", "[Link]" code in your project.


[Make the files empty]

Components in React 19 App:


1. Every component is a function and must be configured inside ".jsx" file.
2. Every component can have 3 files
a) .jsx for design and logic
b) .css for styles
c) .[Link] for testing
(or)
.[Link] for testing
3. Make sure that all component files are in "src" folder.
4. Better to create a folder for every component.

src
|_ components
|_ login
| |_
[Link]
|
|_ [Link]
|
|_ [Link]
|
|_register
|_ [Link]
|_ [Link]
|_ [Link]
5. CSS file is imported into ".jsx"
6. CSS file can't use type selectors for styling. Type selector applies the
styles for all occurrences across components.
7. It is recommended to use Id or class selectors.
Ex:
1. Components/login/[Link]

import './[Link]';
export function Login(){
return(
<div className='login-container'>
<form className='form-container'>
<h3>User Login</h3>
<dl>
<dt>User Name</dt>
<dd><input type="text" /></dd>
<dt>Password</dt>
<dd><input type="password"/></dd>
</dl>
<button>Login</button>
</form>
</div>
)
}

2. Components/login/[Link]

.login-container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.form-container {
border: 2px solid gray;
padding: 10px;
border-radius: 20px;
box-shadow: 5px 2px 2px black;
}

3. Src/[Link]

import { Login } from './components/login/[Link]'

createRoot([Link]('root')).render(
<StrictMode>
<Login />
</StrictMode>,
)

31 December 2025

1. Install following libraries into project from terminal


> npm install bootstrap bootstrap-icons --save

2. Link following files to "[Link]"


import "../node_modules/bootstrap/dist/css/[Link]";
import "../node_modules/bootstrap-icons/font/[Link]";
import "../node_modules/bootstrap/dist/js/[Link]";

3. You can use bootstrap classes and components from any location

in project.

Syntax: Classes
<div className="alert alert-warning">
<input className="form-control">
<button className="btn btn-warning">
Syntax: Dynamic Attributes
data-bs-target
data-bs-toggle
data-bs-dismiss
<button data-bs-dismiss="alert"> Close </button>
Ex: [Link]

import './[Link]';
export function Login(){
return(
<div className='login-container'>
<form className='form-container alert alert-dismissible alert-warning p-3 w-25'>
<h3 className='bi bi-person-circle'> User Login</h3>
<button data-bs-dismiss="alert" className='btn btn-close'></button>
<dl>
<dt>User Name</dt>
<dd><input type="text" className='form-control' /></dd>
<dt>Password</dt>
<dd><input type="password" className='form-control' /></dd>
</dl>
<button className='btn btn-warning w-100'>Login</button>
</form>
</div>
)
}

Note: To get ideas about page designs you can try "Google Stitch".
[Link]
- Go to Web category and give following prompts
- Create a shopping home page
- Navbar at top with brand name, search bar & social icons.
- Features products in cards with 4 x 4 at section area.
- Footer with contact and services.

React Data Binding


- Data Binding is a technique of accessing data from source and updating
into UI elements. It can identify the changes in UI and update back into source.
- Javascript requires lot of DOM methods for data binding.
- React can bind by using a binding expression "{ }".
Syntax:
var name = "John";
<p> Hello ! {name} </p>
<input type="text" value={name} />
- React supports

One-Way-Binding
implicitly.
- It can bind the data with UI elements but will not allow to change.
-

Two-Way-Binding
requires explicit implementation.

Handling Data for component:


- React application uses

"http"
as protocol. - Http is a "

State-less"
protocol.
- It can't remember data between requests.
- Hence is not recommended to store data using variables for a component.
var name = "John"; // not good for component
- Every component has a local state. It is created while creating component.
- You can use local state to store data for component.
- Local state of component can be accessed by using

"useState()"
hook.
- Hook is a predefined business logic. It is a service.
- Server follows
Single Ton
pattern.

useState()
- It is hook provided by react to access the local state of component.
- It returns a getter and setter.
- Getter is used to read and return value from state.
- Setter is used to assign a new value into state.
const [ getter, setter ] = useState(anyValue);
[ getter, setter ] => It is de-structure declaration.

FAQ's:
1. Can we configure state using var & let keywords ?
A. Yes. But not recommended.
2. Why you are using "const" for state?
A. State must be initialized and used, It should not allow declaration and
assignment.
If we configure state with var & let then they allow declaration & assignment, which is not good for state.

3. If you configure using "const" then how you can set a value?
[Const will not allow to assign]
A. We set value not by assignment, it is done by using initialization.
const [price, setPrice] = useState(40);
setPrice = 50; // invalid - assignment to const not allowed
setPrice(50); // valid

01 January 2026

- Data for Component by using State

- useState()

FAQ: When to set state?

Ans: State can be configured to new values on Mount or on any specific

Event. You can't set values into state while creating component.

FAQ: How to configure the Mount phase for component?

Ans: Mount and Unmount are defined by using "useEffect()" hook.

Syntax:
useEffect(()=>{
// actions on mount
},[dependencies])
Every component mounts on first request.

If you want component to mount again, then you have to define the

dependencies.

Binding various data types:

1. Number Type
- A number in Javascript can be any one of the following
signed integer -10
unsigned integer 10
float 3.4
double 23.33
decimal 235.8321
exponent 2e3
hexadecimal 0x9001
binary 0b1010
octa 0o456
big int 9838286462n
- Numbers are presented using following methods
a) toFixed()
b) toPrecision()
c) toLocaleString()
- Style : currency, decimal, percent, unit
- notation: compact, scientific
Syntax:
const [price] = useState(500000);
{ [Link](91en-in', { style: 91currency', currency:'INR' }) }
- Number parsing is also same as in JS.
a) parseInt()
b) parseFloat()
- Verifying number is same. It is done with "isNaN()".
[ returns true if value is not number ]

2. Boolean Type
- It is configured using "true" & "false" keywords.
- React can't display boolean keywords in UI. It can just use them.
- React can't use boolean as number 0 & 1. [0=false, 1=true]
- React JSX can't use statements.
- You have to handle operations using operators or functions.

Syntax:
const [stock] = useState(true);
<p>
{ (stock===true) ? "True" : "False" }
</p>

3. String Type
- React can use all JS string formats with
a) Single Quote
b) Double Quote
c) Backtick
- Backtick represents a string that allows binding expression.
- Javascript data binding expression is "${ }".
- Binding expression is allowed only in string with backticks.
${ } Javascript Data Binding
{ } React Data Binding
Syntax:
const [styleClass] = useState(91bg-danger text-white');
<p className={ `border border-2 p-2 border-warning ${styleCalss}` }>
<p className={ "border border-2 p-2 border-warning " + styleClass}>
- All string manipulations are same as in JS.
Methods / Properties
- length startsWith()
- charAt() endsWith()
- charCodeAt() includes()
- indexOf() match()
- lastIndexOf() toUpperCase()
- slice() toLowerCase() etc.
- split()
- trim()

4. Null & Undefined


- They are same as in Javascript.
- They are defined using keyword "null" & "undefined".

Syntax:
const [name, setName] = useState();
setName(prompt("Enter Name")); // string | null
<p>
{
(name===null) ? "Name is required" : name
}
</p>

5. Symbol
- It is a new Javascript primitive type. - It is used to configure unique hidden fields in object.

Ex:

<script>
var id = Symbol();
var product = {
[id] : 1,
name : "TV",
price: 45000
}
for(var property in product){
[Link](property + "<br>");
}
[Link](product[id]);
</script>
02 January 2026

- Array declaration and memory assignment is same as Javascript.


a) [ ] meta character
b) Array() constructor
Syntax:
const [data] = useState([ 10, 20, 30 ]);
const [data] = useState(new Array("A", "B"));
- You can read elements from array by using following methods
a) forEach() ]
b) map() ] can read all elements from array
c) toString() ]
d) slice()
e) find()
f) filter() etc.
- React can read and present array element only by using "map()".

FAQ: What is difference between map() & forEach()?


Ans: forEach() is void type and will not return data.
map() is an iterator that returns an array of elements.
Syntax:
<ol>
{
[Link] (item => <li> { item } </li> )
}
</ol>
- Every repeating element in list must have a unique "key" property.
- Avoid using "index" as key. It is not good according to programming
standards.
{
[Link] (item => <li key={item}> {item} </li> )
}
Ex: [Link]

import { useEffect, useState } from "react"

export function DataBinding(){

const [menuItems] = useState(['Home', 'Sale', 'Shop', 'Contact', 'Services']);

useEffect(()=>{

},[])

return(
<div className="container-fluid">
<header className="p-2 mt-2 align-items-center bg-light d-flex justify-content-between">
<div>
<span className="bi bi-justify"></span>
<span className="mx-2">Amazon</span>
</div>
<div>
<div className="input-group">
<input type="text" className="form-control" placeholder="search amazon" />
<button className="btn btn-warning bi bi-search"></button>
</div>
</div>
<nav>
{
[Link](item=> <span className="mx-3" key={item}>{item}</span>)
}
</nav>
</header>
<section className="mt-3">
<ul className="list-group w-25">
{
[Link](item => <li className="list-group-item list-group-item-danger" key={item}>{
}
</ul>
<ul className="list-unstyled ms-4">
{
[Link](item=><li key={item}> <input type="checkbox" /> <label>{item}</label> </li
}
</ul>
</section>
</div>
)
}

- All array manipulations are same as in JavaScript.


pop()
shift()
splice()
push()
unshift()
slice()
indexOf()
sort()
reverse() etc.

Binding Object Type


- Object keeps all relative data and logic together.
- Javascript object with data is considered as "JSON".
- It is a key and value collection.
Syntax:
const [product, setProduct] = useState( { id:1, name:"TV", price: 45000 } );
<p> { [Link] } </p>
- All object manipulations are same using following operators and methods
a) Reading all keys from object

[Link]()
for..in

b) Deleting a Key

delete [Link]
c) Find a Key

"key" in object => returns true


d) Hiding a key
Symbol
data type
Ex: [Link]

import { useEffect, useState } from "react"

export function DataBinding(){

const [product, setProduct] = useState({id:1, name:'TV', price:45000, cities:['Delhi','Hyd'], rating:{rat

useEffect(()=>{

},[])

return(
<div className="container-fluid">
<h4>Product Details</h4>
<dl className="ms-4">
<dt>Product Id</dt>
<dd>{[Link]}</dd>
<dt>Name</dt>
<dd>{[Link]}</dd>
<dt>Price</dt>
<dd>{[Link]('en-in', {style:'currency', currency:'INR'})}</dd>
<dt>Shipped To</dt>
<dd>
<ol>
{
[Link](city=> <li key={city}>{city}</li>)
}
</ol>
</dd>
<dt>Ratings</dt>
<dd>
{[Link]} <span className="bi bi-star-fill text-success"></span>
[{[Link]}]
</dd>
</dl>
</div>
)
}

Binding Array of Objects


- Array is a collection.
- Array collection can have object type elements.
- Every object is a key and value collection.
Syntax:
const [data] = useState( [ { key:value }, { key:value } ] )
Ex: [Link]

import { useEffect, useState } from "react"

export function DataBinding(){

const [products] = useState(


[
{Id:1, Name: "TV", Price: 45000},
{Id:2, Name: "Mobile", Price: 12000},
{Id:3, Name: "Watch", Price: 3000}
]
)
useEffect(()=>{

},[])

return(
<div className="container-fluid">
<h3>Products Table</h3>
<table className="table table-hover">
<thead>
<tr>
<th>Name <span className="bi bi-sort-alpha-down"></span> </th>
<th>Price <span className="bi bi-sort-alpha-down"></span> </th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{
[Link](product=>
<tr key={[Link]}>
<td>{[Link]}</td>
<td>{[Link]}</td>
<td>
<button className="btn btn-warning bi bi-pen-fill"></button>
<button className="btn btn-danger bi bi-trash-fill mx-2"></button>
</td>
</tr>
)
}
</tbody>
</table>
</div>
)
}

03 January 2026

- Number

- String

- Boolean

- Null

- Undefined

- Symbol

- Array

- Object

Binding Map Type


- It is a key and value collection same as object.

- Key can be any type.

- It provides implicit methods for manipulation hence it is faster in interactions

when compared to object.

- However it is structure less.

Syntax:

const [data] = useState(new Map());

[Link](key, value);

[Link](key)

[Link](key)

[Link](key)

[Link]

[Link]()

[Link]()

[Link]() etc..

FAQ: What is difference between object & map?

Ans: - Object keys are string type


- Object is slow in interactions as it uses explicit methods.
- It is structured.
- Map keys can be any type.
- It is faster in interactions with implicit methods.
- It is schema less [structure less]

Binding Date Type


- Date values are stored by using "Date()" constructor.
- You can use all date and time methods to get and set date.
Syntax:
const [dept] = useState(new Date()); // loads current date & time
const [dept] = useState(new Date(91year-month-day hrs:min:sec'));
- Date & Time methods are same as in JS.
getHours() setHours()
getMinutes() setMinutes()
getSeconds() setSeconds()
getDay() setDate()
getDate() setMonth()
getMonth() setFullYear() etc..
getFullYear()
toDateString()
toLocaleDateString()
toTimeString()
toLocaleTimeString()
toString() etc.

- Presenting date in a custom format requires lot of coding.

Ex: [Link]

import { useEffect, useState } from "react"

export function DataBinding(){

const [departure] = useState(new Date('2026-02-10 14:32:24'));


const [weekdays] = useState(['Sunday','Monday','Tuesday','Wed','Thu','Friday','Saturday']);
const [months] = useState(['January', 'February', 'March']);

useEffect(()=>{

},[])

return(
<div className="container-fluid">
<h3>Departure : {[Link]()} {weekdays[[Link]()]}, {months[[Link](
</div>
)
}

- React can use various Javascript libraries for manipulating date


and time values.
- The popular JS libraries for date & time
a) moment
b) dayjs
c) luxon
Ex: moment
1. Install moment library for react project
> npm install moment --save
2. Import "moment" into component
import moment from "moment";
3. Apply format to date & time
{ moment(departure).format(91your format') }
ddd Short Weekday
dddd Long Weekday
DD Date number
MMM Short Month
MMMM Long Month
YY Short Year
YYYY Full Year

Ex:
{ moment(departure).format(91dddd DD, MMMM YYYY') }

Ex: [Link]
import { useEffect, useState } from "react"

import moment from "moment";


export function DataBinding(){

const [departure] = useState(new Date('2026-02-10 14:32:24'));

useEffect(()=>{

},[])

return(
<div className="container-fluid p-4">
<h2>Departure : {moment(departure).format('dddd DD, MMMM YYYY')} </h2>
</div>
)
}

Regular Expression Type

- Regular expression is used to verify format of value.

- It is built by using Meta Characters & Quantifiers.

- Expression is enclosed in "/ /".

- Expression is verified by using string "match()" method.

Syntax:

const [regEx] = useState(/ \+91\d{10} /);

const [mobile] = useState("9876543211");

{ ([Link](regEx)) ? "Valid" : "Invalid" }

Ex: [Link]

import { useEffect, useState } from "react"


import moment from "moment";

export function DataBinding(){

const [regEx] = useState(/(?=.*[A-Z])\w{4,15}/);


const [password] = useState('daVid123');

useEffect(()=>{

},[])

return(
<div className="container-fluid p-4">
<p>Your Password : {password}</p>
{
([Link](regEx)) ? "Strong Password": "Weak Password one uppercase letter required"
}
</div>
)
}

JavaScript Ajax Techniques:


- Javascript can handle AJAX requests client side by using

a) XMLHttpRequest Object

b) fetch() Promise

XMLHttpRequest

1. Create a request object

var http = new XMLHttpRequest();

2. Configure request

[Link]("method", "url", async:boolean)

3. Send request

[Link]();

4. Execute request

[Link] = function() {
}

5. Check the request status and capture response

1 Initial

2 Success

3 Complete
4 Ready

if([Link]===4)
{
// [Link] => convert into JSON using "[Link]()"
}

Ex:

public/[Link]

{
"title": "Apple iPhone 16 (Pink, 256 GB)",
"price": 79900,
"image": "[Link]",
"rating": {"rate":4.9, "ratings":160567, "reviews":5822},
"offers": [
"Bank Offer5% cashback on Axis Bank Flipkart Debit Card up to ■ 750T&C",
"Bank Offer5% cashback on Flipkart Axis Bank Credit Card upto ■ 4,000 per statement quarterT&C",
"Bank OfferFlat ■ 400 off on Flipkart Bajaj Finserv Insta EMI Card. Min Booking Amount: ■ 40,000T&C"
]
}

[Link]

import { useEffect, useState } from "react"

export function Flipkart(){

const [product, setProduct] = useState({title:null, price:0, image:null, rating:{rate:0, ratings:0, revie

function LoadData(){
var http = new XMLHttpRequest();
[Link]("get", "[Link]", true);
[Link]();
[Link] = function(){
if([Link]===4){
setProduct([Link]([Link]));
}
}
}
useEffect(()=>{
LoadData();
},[])

return(
<div className="container-fluid">
<div className="mt-4">
<div className="row">
<div className="col-3">
<img width="100%" src={[Link]} />
</div>
<div className="col-9">
<div className="fs-5">{[Link]}</div>
<div className="mt-2">
<span className="badge bg-success text-white rounded">{[Link]} <span cla
<span className="mx-2 text-secondary fw-bold"> {[Link]
</div>
<div className="mt-3 fs-2 fw-bold">
{[Link]('en-in',{style:'currency', currency:'INR', minimumFract
</div>
<div className="mt-3">
<h5>Available Offers</h5>
<ul className="list-unstyled">
{
[Link](offer=>
<li className="bi bi-tag-fill text-success my-4" key={offer}><span classN
)
}
</ul>
</div>
</div>
</div>
</div>
</div>
)
}

05 January 2026

1. XMLHttpRequest
Issues with XMLHttpRequest

- It synchronous by default.

- You have to make it asynchronous explicitly.

- It returns response in text format.

- It requires explicit conversions.

- It is not good in error handling.

- It is not safe as it has issues with XSRF, CORS, XSS.


Cross Site Request Forgery [XSRF]
Cross Origin Resource Sharing [CORS]
Cross Site Scripting Attacks [XSS]

2. Javascript "fetch()" API

- Fetch is promise based function

- It is async by default.

- It uses XMLHttpRequest object implicitly.

- It is better in error handling.

Syntax:
fetch("url")
.then(function(response){
}
.catch(function(error){
}
.finally(function(){
})

Issues with Fetch:

- It is a DOM method.

- It is not good directly for virtual DOM.

- It returns every response in binary format.

- Explicit conversions are required.

- Binary conversions can be blocked by firewalls.

- Not very good in security like CORS, XSRF, XSS etc.

Ex: [Link]
import { useEffect, useState } from "react"

export function Flipkart(){

const [product, setProduct] = useState({title:null, price:0, image:null, rating:{rate:0, ratings:0, revie


function LoadData(){
fetch("[Link]")
.then(function(response){
return [Link]();
})
.then(function(product){
setProduct(product);
})
}
useEffect(()=>{
LoadData();
},[])

return(
<div className="container-fluid">
<div className="mt-4">
<div className="row">
<div className="col-3">
<img width="100%" src={[Link]} />
</div>
<div className="col-9">
<div className="fs-5">{[Link]}</div>
<div className="mt-2">
<span className="badge bg-success text-white rounded">{[Link]} <span cla
<span className="mx-2 text-secondary fw-bold"> {[Link]
</div>
<div className="mt-3 fs-2 fw-bold">
{[Link]('en-in',{style:'currency', currency:'INR', minimumFract
</div>
<div className="mt-3">
<h5>Available Offers</h5>
<ul className="list-unstyled">
{
[Link](offer=>
<li className="bi bi-tag-fill text-success my-4" key={offer}><span classN
)
}
</ul>
</div>
</div>
</div>
</div>
</div>
)
}

React 3rd Party libraries for handling AJAX requests

- React can use various 3rd party libraries for handling AJAX requests.

a) axios

b) whatwg-fetch

c) jQuery Ajax [jquery - native] etc.

Axios for React:

- It uses XMLHttpRequest.

- It is a virtual DOM library.


- It is a promise based library.

- It is async by default.

- It returns data in native format.

- Explicit conversions not required.

- It is good in error handling.

- It is good in security like CORS, XSRF, XSS etc.

- It can cancel requests.

- It can handle multiple requests simultaneously at the same time.


[Link]

1. Install axios for your project


> npm install axios --save

2. Import axios into component


import axios from "axios";

3. Configure axios request


[Link]()
[Link]()
[Link]()
[Link]()
[Link]() etc..

Syntax:
[Link]("url").
then(function(response){
[Link], status, statusCode etc.
})
.catch(function(error){
})
.finally(function(){
})

Ex: [Link]

import { useEffect, useState } from "react"


import axios from "axios";

export function Flipkart(){

const [product, setProduct] = useState({title:null, price:0, image:null, rating:{rate:0, ratings:0, revie

function LoadData(){
[Link]('[Link]')
.then(response=>{
setProduct([Link]);
[Link]([Link]);
})
.catch(error=>{
[Link](error);
})
.finally(()=>{
[Link]('Request End');
})
}
useEffect(()=>{
LoadData();
},[])

return(
<div className="container-fluid">
<div className="mt-4">
<div className="row">
<div className="col-3">
<img width="100%" src={[Link]} />
</div>
<div className="col-9">
<div className="fs-5">{[Link]}</div>
<div className="mt-2">
<span className="badge bg-success text-white rounded">{[Link]} <span cla
<span className="mx-2 text-secondary fw-bold"> {[Link]
</div>
<div className="mt-3 fs-2 fw-bold">
{[Link]('en-in',{style:'currency', currency:'INR', minimumFract
</div>
<div className="mt-3">
<h5>Available Offers</h5>
<ul className="list-unstyled">
{
[Link](offer=>
<li className="bi bi-tag-fill text-success my-4" key={offer}><span classN
)
}
</ul>
</div>
</div>
</div>
</div>
</div>
)
}

Ex:

1. Public/[Link]

[
{
"title": "DHURANDHAR",
"poster": "[Link]",
"language": "Hindi",
"certificate": "A"
},
{
"title": "IKKIS",
"poster": "[Link]",
"language": "Hindi",
"certificate": "UA 13+"
},
{
"title": "THE SPONGEBOB MOVIE",
"poster": "[Link]",
"language": "English",
"certificate": "UA 7+"
},
{
"title": "THE HOUSEMAID",
"poster": "[Link]",
"language": "English",
"certificate": "A"
},
{
"title": "AVATAR : FIRE & ASH",
"poster": "[Link]",
"language": "English",
"certificate": "UA 15+"
}

2. Components/inox/[Link]

import axios from "axios";

import { useEffect, useState } from "react"

export function Inox(){

const [movies, setMovies] = useState([{title:null, poster:null, language:null, certificate:null}]);

function LoadMovies(){
[Link]('[Link]')
.then(response=>{
setMovies([Link]);
})
}

useEffect(()=>{
LoadMovies();
},[])

return(
<div className="container-fluid p-3">
<header>
<div className="text-center fw-bold fs-4">Inox Movies</div>
</header>
<section className="mt-3 d-flex flex-row">
{
[Link](movie=>
<div key={[Link]} className="card m-2 p-2 w-25">
<img src={[Link]} className="card-img-top" height="200"/>
<div className="card-header text-center fw-bold">
{[Link]}
</div>
<div className="card-body">
<dl>
<dt>Language</dt>
<dd>{[Link]}</dd>
<dt>Certificate</dt>
<dd>{[Link]}</dd>
</dl>
</div>
<div className="card-footer">
<button className="btn btn-warning w-100"> Book Ticket </button>
</div>
</div>

)
}
</section>
</div>
)
}

06 January 2026

- XMLHttpRequest

- fetch()

- axios

Connecting with API and fetching data [ Fakestore ]


- Fakestore provides a REST API service
- Representational State Transfer.
- Application Programming Interface
- REST communication
Consumer sends query request => Provider sends JSON response

API Routes [ Fakestore ]


GET /products [ { }, { } ] all products
GET /products/categories [ " " ] all categories
GET /products/category/electronics [ { }, { } ] products of specific category
GET /products/id { } specific product by ID.
Syntax:
[Link]
Data:
{
id: number,
title: string,
image: string,
price: number,
description: string,
category: string,
rating: { rate: number, count: number }
}

Plan UI with Google Stitch:


- Create a shopping Home Screen
- Navbar at the top in header with brand name, search bar and short
cut icons.
- Featured products in section.
- Featured products in cards 4 x 4
- Filter by category, rating and price range in left panel of section

Style Binding in React:


- You can configure inline styles to any JSX element using "style" property.
- Style will accept dynamic object.
<div style={ { } }> </div>
{ } outer block is react binding
{ } inner block is object for style.
- Style have property and value.
- Style properties are defined in camel case.
- Style values are defined string format.
background-color backgroundColor
text-align textAlign
font-size fontSize etc..

Syntax: React
<div style={ { backgroundColor: 91red', color: 91white' } }>

Syntax: HTML
<div style="background-color:red; color:white">
Ex: [Link]

import axios from "axios";


import { useEffect, useState } from "react"

export function Fakestore(){

const [products, setProducts] = useState([{id:0, title:null, price:0, description:null, category:null, im


const [categories, setCategories] = useState([]);

function LoadProducts(url){
[Link](url)
.then(response=>{
setProducts([Link]);
})
}

function LoadCategories(){
[Link](`[Link]
.then(response=>{
[Link]('all');
setCategories([Link]);
})
}

useEffect(()=>{

LoadProducts(`[Link]
LoadCategories();

},[])

return(
<div className="container-fluid">
<header className="d-flex align-items-center justify-content-between p-2 bg-light">
<div>
<span className="bi bi-bag fs-4 fw-bold text-dark"></span>
<span className="fs-4 mx-2 fw-bold">Shopping.</span>
</div>
<div>
<div className="input-group">
<input className="form-control" type="text" placeholder="Search [Link]" />
<button className="btn btn-warning bi bi-search"></button>
</div>
</div>
<div>
<button className="btn bi bi-person"></button>
<button className="btn mx-2 bi bi-heart"></button>
<button className="btn bi bi-cart4"></button>
</div>
</header>
<section className="row mt-2">
<nav className="col-2">

<div className="bg-light p-3">


<div className="d-flex my-3 justify-content-between">
<span className="text-primary">Filters</span>
<span className="text-primary">Clear All</span>
</div>
<div className="mt-3">
<label className="form-label fw-bold">Category</label>
<div>
<select className="form-select">
{
[Link](category=>
<option key={category} value={category}>{[Link]()}</option>
)
}
</select>
</div>
</div>
<div className="mt-3">
<label className="form-label fw-bold">Choose Categories</label>
<div>
<ul className="list-unstyled">
{
[Link](category=>
<li style={{fontSize:'13px'}} className="my-2" key={category}> <input typ
)
}
</ul>
</div>
</div>
<div className="mt-4">
<label className="form-label fw-bold">Price Range</label>
<input type="range" className="form-range" />
</div>
<div className="mt-4">
<label className="form-label fw-bold">Ratings</label>
<ul className="list-unstyled">
<li> 4 <span className="bi bi-star-fill text-warning"></span> <span className
<li className="my-2"> 3 <span className="bi bi-star-fill text-warning"></span
<li> 2 <span className="bi bi-star-fill text-warning"></span> <span className

</ul>
</div>
</div>
</nav>
<main className="col-10 d-flex overflow-auto flex-wrap" style={{height:'500px'}}>
{
[Link](product=>
<div key={[Link]} className="card m-2 p-2" style={{width:'200px'}}>
<img src={[Link]} className="card-img-top" height="100" />
<div className="card-header" style={{height:'120px'}}>
{[Link]}
</div>
<div className="card-body">
<dl>
<dt>Price</dt>
<dd>{[Link]}</dd>
<dt>Rating</dt>
<dd>{[Link]} <span className="bi bi-star-fill text-succe
</dl>
</div>
<div className="card-footer">
<button className="btn w-100 btn-warning bi bi-cart4"> Add to Cart</butto
</div>
</div>
)
}
</main>
</section>
</div>
)
}

07 January 2026

Javascript Event Topics

1. What is Event?

2. What is Event Handler?

3. What is Event Listener?

4. What are Event Arguments?

5. Custom and Default Arguments

6. Event Propagation / Event Bubbling

7. Prevent Default Events


8. Event Loop

9. Event Profiling

What is Event?

- Event is a message sent by sender to its subscriber in order to notify change.

- Event follows a software design pattern called Observer.

- Event uses a delegate mechanism, which is function pointer.

Syntax:
function DeleteClick() { } // subscriber
onclick="DeleteClick()" // sender
Subscriber : defines the actions to perform.

Sender : it is a trigger to perform the actions.


What is Event Handler?

- Event is configured for element in design by using a handler.

<button onclick="DeleteClick()">

on : handler

click : event

What is Event Listener?

- Event listener is used to configure event for elements dynamically.

- Elements added to design dynamically can't have handlers, they are

configured using listeners.

- You can add event to element by using "addEventListener()" method.

Syntax:

[Link]("button").addEventListener("click", function(){
})

Ex:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
function bodyload(){
[Link]("btnDelete").addEventListener("click",()=>{
[Link]("Record Deleted");
})
var button = [Link]("button");
[Link] = "Insert";
[Link]("click",()=>{
[Link]("Inserted..");
})
[Link]("body").appendChild(button);
}
</script>
</head>
<body onload="bodyload()">
<button id="btnDelete">Delete</button>
</body>
</html>

What are Event Arguments?


- Event arguments are used to carry payload. - Payload is the data carried from one location to another.

- Event has 2 default arguments


a) this

b) event

- "this" sends information about current element, which includes

id, name, className, value, src, href, width, height etc.

- "event" sends information about current event, which includes

clientX, clientY, keyCode, charCode, shiftKey etc.

Syntax:
<button onclick="Name(this, event)">
function Name(element, e)
{
[Link], name, value, etc.
[Link], clientY, shiftKey, etc.
}

Ex:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
function Player(element, e){
[Link](`Button Name : ${[Link]}<br>Button Id : ${[Link]}<br>Clicked at X axis p
}
</script>
</head>
<body>

<button onclick="Player(this, event)" id="btnPlay" name="Play">Play</button>


<button onclick="Player(this, event)" id="btnPause" name="Pause">Pause</button>
<button onclick="Player(this, event)" id="btnStop" name="Stop">Stop</button>
</body>
</html>

- You can send custom arguments.

- It can be only custom args or along with default args.

Syntax:

<button onclick="Details(val1, val2, val3,..)">

function Details(param1, param2, param3..) { }

function Details(...params) { }

Ex:
<!DOCTYPE html>

<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
function DetailsClick(element, ...product){
[Link](product);
[Link]([Link]);
}
</script>
</head>
<body>
<button id="btnDetails" onclick="DetailsClick(this, 1, 'TV', true, ['Delhi','Hyd'])">Details</button>
</body>
</html>

- Event listener can have only one argument, which refers to "event".

Syntax:
.addEventListener("click", function(e){
[Link], clientY, shiftKey => event details
[Link], name, value => element details
})

Ex:
<!DOCTYPE html>

<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
function bodyload(){
[Link]("btnDelete").addEventListener("click",(e)=>{
[Link](`Button Id : ${[Link]}\nX Position : ${[Link]}`);
})
}
</script>
</head>
<body onload="bodyload()">
<button id="btnDelete" value="Delete">Delete</button>
</body>
</html>

What is Event Propagation?

- It is a mechanism where the child event may trigger the parent events.

- Child event simulates parent functionality.

- You can prevent by using event method "stopPropagation()".

Syntax:
function ChildEvent(e)
{
[Link]();
}

- Propagation of event is also know as "Event Bubbling".

08 January 2026

- What is Event?
- Event Handler
- Event Listener
- Event Arguments
a) Default Args
b) Custom Args
- Event Propagation
stopPropagation()
- Prevent Default
preventDefault()

What is Event Loop?


- Event loop is the process of executing a set of tasks on specific event.
- Javascript can run given set of tasks using following priority
1st Normal Task
2nd Micro Task
3rd Macro Task
- Normal task refer to general functions.
- Micro task refer to promise based asynchronous functions.
- Macro task refers to debounce using setTimeout.
Ex:

<!DOCTYPE html>

<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
function ExecuteClick(){
setTimeout(()=>{
[Link]('Macro Task');
},0)

[Link]('Normal Task');

var data = new Promise((resolve, reject)=>{


resolve('Micro Task');
})
[Link](res=>{
[Link](res);
})
}
</script>
</head>
<body>
<button onclick="ExecuteClick()">Execute</button>
</body>
</html>

What is event profiling?


- Profiling is the process of tracking performance of events in page.
- It includes event log, call tree etc.
- It provides details about event loop and time consumed for events etc.

React Event Binding


- Javascript events are browser events.
- Browser window object configures events for elements.
- React can't use browser events directly.
- React uses "

Synthetic Events"
library for virtual DOM events.
- SyntheticEvent is the base for all events in virtual DOM.
- SyntheticEvent maps to browser event.
Syntax:
onClick : MouseEvent : EventHandler : SyntheticEventHandler: BaseSynthenticEvent
- SyntheticEvents are defined in camel case.
- Events in react point towards a function in component.
Syntax:
<button onClick={ handleInsertClick } >
function handleInsertClick()
{
}
- Synthetic Event sends default arguments to function.
- The arguments refers to Event Listener.
- Event Listener uses a single argument to handle element & event details.
function handleInsertClick(e)
{
[Link], name, value etc.
[Link], clientY etc.
}
Ex:
[Link]

export function EventBinding(){

function handleInsertClick(e){
[Link](`Button Name : ${[Link]}\nButton Id:${[Link]}\nX Position: ${[Link]}`);
}

return(
<div className="container-fluid p-4">
<button onClick={handleInsertClick} name="Insert" id="btnInsert">Insert</button>
</div>
)
}

- You can configure custom arguments by using a callback function


in event.
Syntax:
<button onClick={ ()=> handleInsertClick(your_args) }>
- You can send both default an custom arguments by using

event
as
a formal parameter in event callback.
Syntax:
<button onClick= { (e) => handleInsertClick(e, your_args) }>
function handleInsertClick(e, ...params)
{
}
- Event Propagation & Preventing default events is same as in JS.
function handleEvent(e)
{
[Link]();
[Link]();
}

Two Way Data Binding


- React implicitly supports "One-Way-Binding".
- Two way binding for elements can be configured only by using the
synthetic event

"onChange".
- You can enable two-way-binding only with "onChange".
- You can configure multiple events for any element in component, but
two-way binding can be enabled only with "onChange".
Syntax:
<input type="text" onChange={ handleChange } />
<select onChange={handleChange} />
<input type="checkbox" onChange={handleChange} />
function handleChange(e)
{
[Link]; // returns element value
}
Ex:

import { useState } from "react"

export function EventBinding(){

const [userName, setUserName] = useState('John');

function handleNameChange(e){
setUserName([Link]);
}

return(
<div className="container-fluid p-4">
<dl>
<dt>User Name</dt>
<dd><input type="text" onChange={handleNameChange} value={userName} /></dd>
</dl>
<h2>Hello ! {userName}</h2>
</div>
)
}

09 January 2026

1. Mouse Events
onMouseOver : actions when mouse pointer is over element.
onMouseOut : when mouse pointer moves out of element.
onMouseDown : when user hold down mouse button on element
onMouseUp : when button is released on element.
onMouseMove : while moving mouse pointer
- The popular properties used with mouse events
a) clientX
b) clientY
Ex: MouseOver
1. public/[Link]

{
"image": "[Link]"
},
{
"image": "[Link]"
},
{
"image": "[Link]"
},
{
"image": "[Link]"
}
]

2. Components/mouse-demo/[Link]

.mobile-container {

border:4px solid gray;


}

.mobile-container:hover {
border:4px solid blue;
cursor: grab;
}

3. Components/mouse-demo/[Link]

import axios from "axios";

import { useEffect, useState } from "react"


import './[Link]';

export function MouseDemo(){

const [mobiles, setMobiles ] = useState([{image:null}]);


const [previewImage, setPreviewImage] = useState('[Link]');
function LoadMobiles(){
[Link]('[Link]')
.then(response=>{
setMobiles([Link]);
})
}
useEffect(()=>{
LoadMobiles();
},[])

function handleMouseOver(e){
setPreviewImage([Link]);
}

return(
<div className="container-fluid p-3">
<div className="row mt-4">
<div className="col-2">
{
[Link](mobile=>
<div key={[Link]} className="my-4 mobile-container" style={{width:'100px'}}
<img src={[Link]} onMouseOver={handleMouseOver} width="100%" height="10
</div>
)
}
</div>
<div className="col-10">
<img width="400" height="500" src={previewImage} />
</div>
</div>
</div>
)
}

Ex: MouseUp & Down


[Link]

@keyframes Spin {

from {
transform: rotate(0deg) scale(1);
}
to {
transform: rotate(360deg) scale(2);
}
}

[Link]

import { useState } from 'react';

import './[Link]';

export function MouseAnimation(){

const [animationObject, setAnimationObject] = useState({animationName:'Spin', animationDuration:'3s', ani

function handleMouseDown(){
setAnimationObject({animationName:'Spin', animationDuration:'500ms', animationIterationCount:'infinit
}
function handleMouseUp(){
setAnimationObject({animationName:'Spin', animationDuration:'3s', animationIterationCount:'infinite',
}

return(
<div className="d-flex justify-content-center align-items-center" style={{height:'100vh'}}>
<img onMouseDown={handleMouseDown} onMouseUp={handleMouseUp} src="[Link]" style={animationObj
</div>
)
}

Ex: Mouse Move


[Link]

import { useState } from "react"

export function MouseMove(){

const [styleObj, setStyleObject] = useState({position:'fixed', top:'', left:''});

function handleMouseMove(e){
setStyleObject({position:'fixed', top:`${[Link]}px`, left:`${[Link]}px`});
}

return(
<div onMouseMove={handleMouseMove}>
<div style={{height:'1000px'}}>
<p className="fs-2">Move mouse pointer to test</p>
</div>
<img src="[Link]" style={styleObj} width="50" height="50" />
</div>
)
}

2. Keyboard Events
onKeyUp
onKeyDown
onKeyPress [deprecated]
-

KeyUp & KeyDown


are good for handling actions related to chars that
user input.
-

KeyPress
is good for handling character ASCII code. However it is
deprecated and character code can be accessed using "charCodeAt()"
function.

10 January 2026

1. Mouse Events
2. Keyboard Events
Ex:
[Link]

import axios from "axios";


import { useEffect, useState } from "react"
export function KeyDemo(){

const [users, setUsers] = useState([{username:null}]);


const [userMsg, setUserMsg] = useState('');
const [userClass, setUserClass] = useState('');
const [progressWidth, setProgressWidth] = useState({width:null});
const [strengthColor, setStrengthColor] = useState('');
const [passwordMsg, setPasswordMsg] = useState('');

function LoadUsers(){
[Link]('[Link]')
.then(response=>{
setUsers([Link]);
})
}

useEffect(()=>{
LoadUsers();
},[])

function verifyUser(e){
for(var user of users)
{
if([Link]===[Link]){
setUserMsg('User Name Taken - Try Another');
setUserClass('text-danger');
break;
} else {
setUserMsg('User Name Available');
setUserClass('text-success');
}
}
}

function VerifyPassword(e){
if([Link](/(?=.*[A-Z])\w{4,15}/)) {
// strong
setProgressWidth({width:'100%'})
setStrengthColor('bg-success');
setPasswordMsg('Strong Password');
} else {
if([Link]<4){
// poor
setProgressWidth({width:'30%'})
setStrengthColor('bg-danger');
setPasswordMsg('Poor Password');
} else {
// weak
setProgressWidth({width:'70%'});
setStrengthColor('bg-warning');
setPasswordMsg('Weak Password');
}
}
}

return(
<div className="container-fluid p-4">
<h3>Register User</h3>
<dl className="w-25">
<dt>User Name</dt>
<dd><input type="text" className="form-control" onKeyUp={verifyUser} /></dd>
<dd className={userClass}>{userMsg}</dd>
<dt>Password</dt>
<dd>
<input onKeyUp={VerifyPassword} className="form-control" type="password" />
</dd>
<dd>
<div className="progress">
<div className={`progress-bar text-white progress-bar-striped progress-bar-animated ${s
{passwordMsg}
</div>
</div>
</dd>
</dl>
</div>
)
}

3. Button Events
onClick
onDoubleClick
onContextMenu
onSelectStart
- Button events can handle various interactions, but require actual DOM
events to manage browser actions.
[Link]
[Link]
[Link]
- You can disable any event by configuring a function that returns false.
function handle()
{
[Link] = function() {
return false;
}
}
Ex:
[Link]

export function ButtonDemo(){

function handleDoubleClick(){
[Link]('[Link]','iPhone','width=300 height=400');
}

function handleContextMenu(){
[Link] = ()=>{
alert('Right Click Not Allowed');
return false;
}
}

return(
<div onContextMenu={handleContextMenu} className="container-fluid p-4">
<h1>Highly Confidential</h1>
<p>Right click not allowed on this page</p>
<img onDoubleClick={handleDoubleClick} src="[Link]" width="50" height="50" />
<p>Double Click to View Large</p>

</div>
)
}

19 January 2026

- Mouse Events

- Keyboard Events

- Button Events

- Clipboard Events

Element State Events:


onChange
onFocus
onBlur
-

onChange
defines actions to perform while changing the value in element.
-

onFocus
defines actions when element is in focus.
-

onBlur
defines actions when element looses the focus.
Ex:
[Link]

import { useState } from "react"

export function ElementState()


{
const [userName, setUserName] = useState('');
const [msg, setMsg] = useState('');

function handleNameBlur(){
setUserName([Link]());
setMsg('');
}
function handleNameChange(e){
setUserName([Link]);
}

function handleNameFocus(){
setMsg('Name in Block Letters');
}

return(
<div className="container-fluid">
<h2>Register</h2>
<dl className="ms-4">
<dt>User Name</dt>
<dd><input type="text" value={userName} onFocus={handleNameFocus} onChange={handleNameChange}
<dd className="text-warning fs-6">{msg}</dd>
</dl>
</div>
)
}

Ex: EMI Calculator

import { useState } from "react"

export function EMICalcualtor(){

const [loanAmount, setLoanAmount] = useState(25000);


const [year, setYears] = useState(1);
const [rate, setRate] = useState(10.45);
const [emi, setEMI] = useState(0);

function CalculateEMI(){
var P = parseInt(loanAmount);
var R = parseFloat(rate)/12/100;
var N = parseInt(year) * 12;
var emi = P * R * ([Link](1+R,N)) / ([Link](1+R,N)) - 1;
setEMI(emi);
}

function handleAmountChange(e){
setLoanAmount([Link]);
CalculateEMI();
}
function handleYearChange(e){
setYears([Link]);
CalculateEMI();
}

function handleRateChange(e){
setRate([Link]);
CalculateEMI();
}

function handleCalculateClick(){
var P = parseInt(loanAmount);
var R = parseFloat(rate)/12/100;
var N = parseInt(year) * 12;
var emi = P * R * ([Link](1+R,N)) / ([Link](1+R,N)) - 1;
setEMI(emi);
}

return(
<div className="container-fluid" style={{height:'100vh'}}>
<div className="row mt-4">
<div className="col-6">
<div className="row">
<div className="d-flex justify-content-between">
<div><label className="form-label fw-bold">Loan Amount</label></div>
<div><input type="text" onChange={handleAmountChange} value={loanAmount} className="
</div>
<div>
<input type="range" onChange={handleAmountChange} min="25000" value={loanAmount} step
<div>
<span>&#8377; 25,000/-</span>
<span className="float-end">&#8377; 10,00,000/-</span>
</div>
</div>
</div>
<div className="row my-3">
<div className="d-flex justify-content-between">
<div><label className="form-label fw-bold">Loan Tenure</label></div>
<div><input onChange={handleYearChange} style={{width:'50px'}} value={year} type="t
</div>

<div>
<input type="range" onChange={handleYearChange} min="1" max="7" value={year} classNam
<div>
<span>1 Year</span>
<span className="float-end">7 Years</span>
</div>
</div>
</div>
<div className="row my-3">
<div className="d-flex justify-content-between">
<div><label className="form-label fw-bold">Loan Interest</label></div>
<div><input type="text" onChange={handleRateChange} value={rate} style={{width:'70p
</div>
<div>
<input type="range" onChange={handleRateChange} value={rate} min="10.45" step="0.01"
<div>
<span>10.45%</span>
<span className="float-end">18.45%</span>
</div>
</div>
</div>
<div className="text-center">
<button onClick={handleCalculateClick} className="btn btn-primary">Calculate</button>
</div>
</div>
<div className="col-6 ps-4">
<h3>Loan Installment Amount</h3>
<div className="h1">
{[Link]('en-in', {style:'currency', currency:'INR', minimumFractionDigits
</div>
</div>
</div>
</div>
)
}

Timer Events

20 January 2026

- setTimeout()

- clearTimeout()

- setInterval()

- clearInterval()

Debounce

- A computing device executes tasks inside process at high speed.


- A set of tasks provided to processor will execute immediately.

- The process of locking a task in memory for specific duration of time

and later releasing into process is known as "Debounce".

- The events used to control debounce are:


a) setTimeout()
b) clearTimeout()

Syntax:
setTimeout(function(){ }, interval);
clearTimeout(referenceName);

useRef() Hook:

- It configures a reference memory.

- You can store any value or function into reference memory.

- It is intended to use inside the process instead of rendering into UI.

- It improves the performance of application while handling multiples

tasks in memory.

Syntax:
let thread = useRef(null);

- You can configure any task using "current" property.


[Link] = value / function;

- You can access using "current" thread property


setTimeout([Link]);

Ex:

[Link]

import { useRef, useState } from "react"

export function DebounceDemo(){

const [msg, setMsg] = useState('');

let thread = useRef(null);

function Level1(){
setMsg('Volume Increased : 20%');
}
function Level2(){
setMsg('Volume Increased : 70%');
}
function Level3(){
setMsg('Volume Full');
}
function VolumeUpClick(){
setTimeout(Level1, 3000);
[Link] = setTimeout(Level2, 6000);
setTimeout(Level3, 10000);
}
function handleCancelClick(){
alert('Canceled');
clearTimeout([Link]);
}

return(
<div className="container-fluid p-4">
<button onClick={VolumeUpClick} className="btn btn-warning bi bi-volume-up"></button>
<button onClick={handleCancelClick} className="btn btn-danger mx-2">Cancel Level2</button>
<p className="fs-4">{msg}</p>
</div>
)
}

Throttle

- Throttle is a mechanism of executing set of actions repeatedly until stopped.

- It loads a task into memory and releases a copy of task into process at

regular time intervals.

- It repeats until removed from memory.

Syntax:

setInterval( function(){ } , interval);

clearInterval(referenceName);

Ex:
[Link]

import { useEffect, useState } from "react"

export function ThrottleDemo(){

const [now, setNow] = useState(new Date());

function LoadTime(){
setNow(new Date());
}

useEffect(()=>{
setInterval(LoadTime, 1000);
},[])

return(
<div className="container-fluid text-center">
<div className="h1">{[Link]()}</div>
</div>
)
}
Task: Create a Stop Watch using Throttle

21 January 2026

import { useEffect, useRef, useState } from "react"

export function ThrottleDemo(){

const [milliSeconds, setMilliSeconds] = useState(0);


const [seconds, setSeconds] = useState(0);

let thread = useRef(null);

let ms=0, sec=0, min=0, hrs=0;


function StartWatch(){
ms++;
if(ms===999){
ms=0;
sec++;
if(sec===59){
min++;
sec=0;
}
}
setMilliSeconds(ms);
setSeconds(sec);
}

function handleStartClick(){
[Link] = setInterval(StartWatch,1);
}

function handleStopClick(){
clearInterval([Link]);
}

return(
<div className="container-fluid text-center p-4">
<div className="bg-primary p-4 text-white fw-bold fs-1 w-75 row">
<div className="col">
00
</div>
<div className="col">
:
</div>
<div className="col">
00
</div>
<div className="col">
:
</div>
<div className="col">
{seconds}
</div>
<div className="col">
:
</div>
<div className="col">
{milliSeconds}
</div>
<div className="mt-3 fs-5">
<button onClick={handleStartClick} className="btn btn-light">Start</button>
<button onClick={handleStopClick} className="btn btn-warning mx-2">Stop</button>
</div>
</div>

</div>
)
}

Ex: [Link]

import axios from "axios";


import { useEffect, useRef, useState } from "react"

export function CarouselDemo(){

const [product, setProduct] = useState({id:0, title:null, image:null, category:null, description:null, pr


const [status, setStatus] = useState('');

let ProductId = useRef(1);


let thread = useRef(null);

function LoadProductManually(id)
{
[Link](`[Link]
.then(response=>{
setProduct([Link]);
})
}

function LoadProductAuto(){
[Link] = [Link] + 1;
LoadProductManually([Link]);
}

function handlePlayClick(){
[Link] = setInterval(LoadProductAuto, 5000);
setStatus('Slide Show - Started');
}
function handlePauseClick(){
clearInterval([Link]);
setStatus('Slide Show - Paused');
}

function handleNextClick(){
[Link] = [Link] + 1;
LoadProductManually([Link]);
setStatus('Slide Show - Manual');
}
function handlePrevClick(){
[Link] = [Link] - 1;
LoadProductManually([Link]);
setStatus('Slide Show - Manual');
}

function handleSkeebarChange(e){
[Link] = [Link];
LoadProductManually([Link]);
}
useEffect(()=>{
LoadProductManually(1);
},[])

return(
<div className="container-fluid d-flex justify-content-center">
<div className="card mt-3 p-2 w-50">
<div className="card-header text-center overflow-auto" style={{height:'80px'}}>
{[Link]}
<div className="fw-bold">
{status}
</div>
</div>
<div className="card-body">
<div className="row">
<div className="col-1 d-flex flex-column justify-content-center align-items-center">
<button onClick={handlePrevClick} className="bi btn btn-dark bi-chevron-left"></b
</div>
<div className="col-10 position-relative">
<div className="badge bg-danger text-white rounded rounded-circle p-3 fs-5 positi
<img width="100%" src={[Link]} height="300" />
<div>
<input value={[Link]} onChange={handleSkeebarChange} className="fo
</div>
</div>
<div className="col-1 d-flex flex-column justify-content-center align-items-center">
<button onClick={handleNextClick} className="bi btn btn-dark bi-chevron-right"></
</div>
</div>
</div>
<div className="card-footer text-center">
<button onClick={handlePlayClick} className="btn btn-warning bi bi-play"></button>
<button onClick={handlePauseClick} className="btn btn-danger bi bi-pause mx-2"></button>
</div>
</div>
</div>
)
}

Summary
- setTimeout()

- clearTimeout()

- setInterval()

- clearInterval()

Form Events

onSubmit

onReset

- Form events are configured for <form> element.

- They can trigger only with generic buttons like submit & reset.

- You can define actions to perform on submit & on reset.


Syntax:

<form onSubmit={handleSubmit} onReset={handleReset}>


<button type="submit"> Submit </button>
<button type="reset"> Cancel </button>

</form>

Events Summary:

- Mouse Events

- Keyboard Events

- Button Events

- Clipboard Events

- Element State Events

- Timer Events

- Form Events
Conditional Rendering in React

- It is the process of rendering various content according to state and situation.

- React component can handle conditional rendering using following techniques:

1. Rendering a component into the UI according to state and situation

- You have to configure a reference to handle component.

const [component, setComponent] = useState(null);

- You can render any component according to the state and situation

function handleAClick()
{
setComponent( <A/> );
}
function handleBClick()
{
setComponent( <B /> );
}

Ex: [Link]
import { useState } from "react"

import { Login } from "../login/login";


import { Register } from "../register/register";

export function ConditionalRender(){

const [component, setComponent] = useState(null);


function handleLoginClick(){
setComponent(<Login />);
}
function handleRegisterClick(){
setComponent(<Register />);
}

return(
<div className="container-fluid p-5">
<h2>Home</h2>
<button onClick={handleLoginClick} className="btn btn-primary mx-2">Login</button>
<button onClick={handleRegisterClick} className="btn btn-success">Register</button>
<hr />
{component}
</div>
)
}

2. Rendering a part of UI inside component according to state and situation

- You can render various blocks inside component.

- It requires a simple decision making function inside UI.

Syntax:
{
(isActive===true) ? <A /> : <B />
}

- If "isActive" true then it renders <A> block else <B> block.

Ex: [Link]
import { useState } from "react"

import { Login } from "../login/login";


import { Register } from "../register/register";

export function ConditionalRender(){

const [isSignedIn, setIsSignedIn] = useState(false);

function handleSignIn(){
setIsSignedIn(true);
}
function handleSignout(){
setIsSignedIn(false);
}

return(
<div className="container-fluid p-2">
<header className="d-flex border border-2 border-secondary justify-content-between align-items-ce
<div>
<span className="bi bi-amazon"> Amazon </span>
</div>
<div>
{
(isSignedIn===true)
?
<div>
<span className="badge fs-5 bg-danger text-white rounded rounded-circle">
<span className="bi bi-person"></span>
</span>
<button onClick={handleSignout} className="btn btn-link">Signout</button>
</div>
:
<div className="input-group">
<input className="form-control" type="text" placeholder="User Name" />
<button onClick={handleSignIn} className="btn btn-danger"> Signin</button>
</div>
}

</div>
</header>
</div>
)
}

22 January 2026

1. Render a new component according to state and situation.

2. Render a block inside component

Controlled Components

- Component comprises of presentation, styles and logic.


- If any component presentation, style and logic can be changed by the data

passed from parent component, then it is known Controlled Component.

- The component presentation, style and logic can be controlled by using

properties. [ Props ]

- Controlled component is a function with "Props" as parameters.

Syntax:
function Component(props)
{
}

- "Props" is object type with "Key / Value" collection.

Syntax:
{
return(
<div {[Link]}> </div>
)
}
- Keys are dynamic references, you can define any name. But have to access only by specified name.

- A controlled component can change and conditionally render different

layouts.

Syntax:
function Component(props)
{
if([Link]==="value")
{
return( <A />);
}
else
{
return (<B /> );
}
}

Ex:

src/controlled-components/[Link]

export function Navbar(props)


{
if([Link]==='horizontal') {
return(
<nav className={`d-flex flex-row ${[Link]} my-2 justify-content-between align-items-center p-4 b
<div>
<span className={[Link]}></span>
<span className="fw-bold">{[Link]}</span>
</div>
<div>
{
[Link](item=> <span className="mx-3" key={item}>{item}</span>)
}
</div>
<div>
<span className="bi bi-heart"></span>
<span className="bi bi-person mx-4"></span>
<span className="bi bi-gift"></span>
</div>
</nav>
)
} else {
return(
<nav className={`d-flex flex-column ${[Link]} my-2 justify-content-between align-items-center p-
<div>
<span className={[Link]}></span>
<span className="fw-bold">{[Link]}</span>
</div>
<div>
{
[Link](item=> <span className="my-4 btn w-100 btn-light d-block" key={item}>
}
</div>
<div>
<span className="bi bi-heart"></span>
<span className="bi bi-person mx-4"></span>
<span className="bi bi-gift"></span>
</div>
</nav>
)
}
}

src/components/home-demo/[Link]
import { Navbar } from "../../controlled-components/navbar";

export function HomeDemo(){


return(
<div className="container-fluid">
<Navbar orientation="horizontal" logo="bi bi-amazon" theme="bg-primary text-white" brand="Amazon"
<Navbar orientation="vertical" logo="bi bi-facebook" theme="bg-success text-light" brand="Fashion
</div>
)
}

Src/controlled-components/[Link]

export function DataGrid(props){


return(
<table className="table caption-top table-hover">
<caption>{[Link]}</caption>
<thead>
<tr>
{
[Link]([Link][0]).map(key=> <th key={key}>{key}</th>)
}
<th>
Actions
</th>
</tr>
</thead>
<tbody>
{
[Link](item =>
<tr key={item}>
{
[Link](item).map(key=> <td key={key}>{item[key]}</td>)
}
<td>
<button className="btn btn-danger bi bi-trash"></button>
<button className="btn btn-warning mx-2 bi bi-pen"></button>
<button className="btn btn-primary bi bi-eye"></button>
</td>
</tr>
)
}
</tbody>
</table>
)
}

Src/components/home-demo/[Link]
import { useState } from "react"

import { DataGrid } from "../../controlled-components/data-grid";

export function HomeDemo(){


const [products] = useState([{Name:'TV', Price:34000}, {Name:'Mobile', Price:40000}]);
const [employees] = useState([{FirstName: 'Raj', LastName:'Kumar', Desigation:'Manager', Salary: 45000},
return(
<div className="container-fluid">
<DataGrid caption="Products Table" data={products} />
<DataGrid caption="Employee Details" data={employees} />
</div>
)
}

23 January 2026

- Props

FAQ: What is "Props Drilling"?

Ans: It is a mechanism of transporting data from parent to child, where child can
be nested.

Parent can't send data to nested child it requires property drilling technique.
Parent => Child => Child
[level1] [level2]

FAQ: How to avoid Property Drilling?

Ans : By using Context API.


React Context API

- Context is the memory allocated for a page.

- Context memory is accessible to any page that run within the context of parent.

- Context is accessible from any level of hierarchy.

- React provides a Context API, which allows to create a context for parent and
use the

context across components at multilevel hierarchy.

1. Create a context memory for parent

import { createContext } from "react";

let ContextName = createContext(null);

- React 19x version context name must be in Pascal Case.


2. Parent component must configure the context scope with value as provider.

<ContextName value={data}>
.... your child components ....

</ContextName>

- Context data is accessible only to the child components that run inside context
scope.

3. Child component can access and use the context memory by using
useContext() hook.

let context = useContext(ContextName);

context => contains data from parent

Ex: [Link]

import { createContext, useContext, useState } from "react"

let UserContext = createContext(null);

export function Level1(){

let context = useContext(UserContext);

return(
<div className="bg-dark text-white p-4">
<h4>Level-1 - Hello ! {context} </h4>
<Level2 />
</div>
)
}

export function Level2(){


let context = useContext(UserContext);

return(
<div className="bg-warning text-white p-4">
<h4>Level-2 - Hi ! {context}</h4>
</div>
)
}

export function ContextDemo(){

const [uname, setUName] = useState('');

function handleNameChange(e){
setUName([Link]);
}

return(
<div className="container-fluid p-4 bg-danger text-white">
<h3>Parent Component <input onChange={handleNameChange} type="text" placeholder="User name" /> </
<UserContext value={uname}>
<Level1 />
</UserContext>

</div>
)
}

FAQ: Why you need context API if data can be transported from parent to child
using "Props"?

Ans: If child component is not a controlled component then data it transported


using
Context, as it doesn't have any props.
If child component is nested in hierarchy then props drilling is required, which you
can avoid using Context API.

Ex: Weather App

1. Create a new free account at "[Link]

2. Login into your account to get API Key. [ My Profile => My API Keys ]
1318ca6725c69160d346c41fc0612596

3. Go to API docs

4. Select Current Weather Data

5. Select "Request API by City Name"

[Link] name}&appid=HYPERLINK
"[Link] key}

[Link]
1318ca6725c69160d346c41fc0612596&units=metric

Ex:

[Link]
import { WeatherDetails } from "./weather-details";

export function WeatherApp(){


return(
<div className="container-fluid bg-secondary d-flex justify-content-center align-items-center" style=
<div className="p-4 bg-light w-50 rounded rounded-2" style={{height:'400px'}}>
<div>
<h3 className="text-center bi bi-cloud-rain"> Weather App</h3>
<div className="input-group">
<input type="text" className="form-control" placeholder="Your city name" />
<button className="btn btn-warning bi bi-search"></button>
</div>
<div className="mt-4">
<WeatherDetails />
</div>
</div>
</div>
</div>
)
}

[Link]
import axios from "axios";

import { useEffect, useState } from "react"

export function WeatherDetails(){

const [weatherObj, setWeatherObj] = useState({weather:[], main:{temp:0}, name:null});

function LoadWeatherData(){
[Link](`[Link]
.then(response=>{
setWeatherObj([Link]);
})
}

useEffect(()=>{
LoadWeatherData();
},[])

return(
<div className="bg-light shadow shadow-lg p-3">
<h3>{[Link]}</h3>
<div className="fs-1 fw-bold">
{[Link]}&deg;C
</div>
<div>
{[Link][0].description}
</div>
</div>
)
}

24 January 2026

1. Components/weather-app/[Link] [parent]
import { useState } from "react";

import { WeatherDetails } from "./weather-details";

export function WeatherApp(){

const [cityName, setCityName]= useState('');


const [city, setCity] = useState('');
const [toggleDetails, setToggleDetails] = useState('d-none');

function handleCityChange(e){
setCityName([Link]);
}
function handleSearchClick(){
setCity(cityName);
setToggleDetails('d-block');
}

return(
<div className="container-fluid bg-secondary d-flex justify-content-center align-items-center" style=
<div className="p-4 bg-light w-50 rounded rounded-2" style={{height:'400px'}}>
<div>
<h3 className="text-center bi bi-cloud-rain"> Weather App</h3>
<div className="input-group">
<input onChange={handleCityChange} type="text" className="form-control" placeholder="
<button onClick={handleSearchClick} className="btn btn-warning bi bi-search"></button
</div>
<div className={`mt-4 ${toggleDetails}`}>
<WeatherDetails city={city} />
</div>
</div>
</div>
</div>
)
}

2. Components/weather-app/[Link] [child]

import axios from "axios";


import { useEffect, useState } from "react"

export function WeatherDetails(props){

const [weatherObj, setWeatherObj] = useState({weather:[{description:null}], main:{temp:0}, name:null});

function LoadWeatherData(){
[Link](`[Link]
.then(response=>{
setWeatherObj([Link]);
})
}

useEffect(()=>{
LoadWeatherData();
},[props])

return(
<div className="bg-light shadow shadow-lg p-3">
<h3>{[Link]}</h3>
<div className="fs-1 fw-bold">
{[Link]}&deg;C
</div>
<div>
{[Link][0].description}
</div>
</div>
)
}

Ex: Transporting Data from parent to child using Context

1. Components/weather-app/[Link] [parent]
import { createContext, useState } from "react";
import { WeatherDetails } from "./weather-details";

export let CityContext = createContext(null);

export function WeatherApp(){

const [cityName, setCityName]= useState('');


const [city, setCity] = useState('');
const [toggleDetails, setToggleDetails] = useState('d-none');

function handleCityChange(e){
setCityName([Link]);
}

function handleSearchClick(){
setCity(cityName);
setToggleDetails('d-block');
}

return(
<div className="container-fluid bg-secondary d-flex justify-content-center align-items-center" style=
<div className="p-4 bg-light w-50 rounded rounded-2" style={{height:'400px'}}>
<div>
<h3 className="text-center bi bi-cloud-rain"> Weather App</h3>
<div className="input-group">
<input onChange={handleCityChange} type="text" className="form-control" placeholder="
<button onClick={handleSearchClick} className="btn btn-warning bi bi-search"></button
</div>
<div className={`mt-4 ${toggleDetails}`}>
<CityContext value={city}>
<WeatherDetails />
</CityContext>
</div>
</div>
</div>
</div>
)
}

2. Components/weather-app/[Link] [child]

import axios from "axios";


import { useContext, useEffect, useState } from "react"
import { CityContext } from "./weather-app";

export function WeatherDetails(){

const [weatherObj, setWeatherObj] = useState({weather:[{description:null}], main:{temp:0}, name:null});

let context = useContext(CityContext);

function LoadWeatherData(){
[Link](`[Link]
.then(response=>{
setWeatherObj([Link]);
})
}

useEffect(()=>{
LoadWeatherData();
},[context])
return(
<div className="bg-light shadow shadow-lg p-3">
<h3>{[Link]}</h3>
<div className="fs-1 fw-bold">
{[Link]}&deg;C
</div>
<div>
{[Link][0].description}
</div>
</div>
)
}

FAQ: How to transport data from child to parent component?

Ans: You can use various global state management techniques for storing data
globally

and access from any component.

If you want to transport data from child to parent without explicit state
management

then you can use "Custom Events".

1. Design a child component with custom event.

2. Custom events are configured as parameters.

3. Events are object type, you can configure multiple events with key references.

Syntax:

function ChildComponent( { customEventName } )


{
}

4. Custom event of child component can store data, which can be any type data.
{
let data = any;
customEventName(data);
}

5. Data is transported using a trigger, which can any of default Synthetic Events.

function handleButtonClick()
{
customEventName(data);
}

6. Parent component can access the child event data using event binding
technique.

Data is defined as event argument.


<ChildComponent customEventName= {parentHandler } >

function parentHandler(e)
{
e => contains data from child.
}

Ex:

[Link]
import { useState } from "react";

import { ChildComponent } from "./child-component";

export function ParentComponent(){

const [msg, setMsg] = useState('waiting for data from child');

function handleChildComponentClick(e){
setMsg(e);
}

return(
<div className="container-fluid text-white bg-danger p-4">
<h2>Parent Component - {msg}</h2>
<ChildComponent onChildClick={handleChildComponentClick} />
</div>
)
}

[Link]

export function ChildComponent({onChildClick}){

function handleClick(){
let data = 'Hello from child';
onChildClick(data);
}

return(
<div className="p-4 bg-warning">
<h4>Child Component</h4>
<button onClick={handleClick} className="btn btn-light">Send Data to parent</button>
</div>
)
}
26 January 2026

- Form provides an UI for interacting with the data.

- It handles CRUD operations like querying, inserting, updating and deleting.

- Handling a form using React native techniques is always complex.

- It requires lot of two way binding techniques to configure.

- Every element requires "onChange" event.

- React projects use various 3rd party services

a) Formik

b) React Hook Form

c) Telerik Forms etc.

Ex: Without Library - [Link]

import { useState } from "react"

export function FormDemo(){

const [uname, setUserName]= useState('');


const [age, setAge] = useState(0);
const [city, setCity] = useState('');

function handleNameChange(e){
setUserName([Link]);
}

function handleAgeChange(e){
setAge([Link]);
}
function handleCityChange(e){
setCity([Link]);
}
function handleRegisterClick(e){
[Link]();
[Link](`User Name : ${uname}\nAge : ${age}\n City : ${city}`);
}
return(
<div className="container-fluid">
<h2>Register User</h2>
<form>
<dl>
<dt>User Name</dt>
<dd><input type="text" onChange={handleNameChange} /></dd>
<dt>Age</dt>
<dd><input type="text" onChange={handleAgeChange} /></dd>
<dt>Your City</dt>
<dd>
<select onChange={handleCityChange}>
<option>Select City</option>
<option>Delhi</option>
<option>Hyd</option>
</select>
</dd>
</dl>
<button onClick={handleRegisterClick}>Register</button>
</form>
</div>
)
}

Formik Library

- It provides pre-defined methods and events for handling forms in React.

- It uses "useFormik()" hook to configure a form.

- You can bind with any form and interact with the form data.

- It can integrate various validation services and functions.

1. Install formik for project


> npm install formik

2. Import "useFormik" from formik library


import { useFormik } from "formik";

3. Configure a form using useFormik hook


const formik = useFormik( {
initialValues: { },
validate: function() { },
validationSchema: { },
onSubmit: (values) => { },
enableReinitialize: true / false
})

- initialValues refer to the fields that map to form fields.

- validate uses a function that defines custom validations.

- validationSchema is used to configure a pre-defined validation service.

- onSubmit refers to a function that submits form data to server.

- enableReinitialize is used to enable or disable 2 way binding.

4. Make sure that every form element have a reference "name" that maps to

formik initialValues.
<input type="text" name="UserName" />

5. Formik provides "handleChange", which is a default event designed to

collect data from form element.

<input type="text" name="UserName" onChange={[Link]} />


6. Formik provides "handleSubmit", which is a default event used to collect

the form data when submitted to server.

<form onSubmit={[Link]}>

</form>

Ex: [Link]

import { useFormik } from "formik";

export function FormDemo(){

const formik = useFormik({


initialValues: {
UserName: '',
Age: 0,
City: '',
Gender: ''
},
onSubmit : (user) => {
[Link](user);
}
})

return(
<div className="container-fluid">
<h2>Register User</h2>
<form onSubmit={[Link]}>
<dl>
<dt>User Name</dt>
<dd><input type="text" onChange={[Link]} name="UserName" /></dd>
<dt>Age</dt>
<dd><input type="text" onChange={[Link]} name="Age" /></dd>
<dt>Your City</dt>
<dd>
<select onChange={[Link]} name="City" >
<option>Select City</option>
<option>Delhi</option>
<option>Hyd</option>
</select>
</dd>
<dt>Choose Gender</dt>
<dd>
<input type="radio" name="Gender" value="Male" onChange={[Link]} /> Male
<input type="radio" name="Gender" value="Female" onChange={[Link]} /> Fe
</dd>
</dl>
<button type="submit">Register</button>
</form>
</div>
)
}

Formik Validation

- Validation is the process of verifying user input.

- Validation is required to ensure that contradictory and unauthorised data


is not get stored into database.

- You can configure custom validations or use predefined validation services.

Custom Validation:

- You can write explicit validations by using various Javascript properties

and methods.

- Formik can use your custom functions to validate the form field.

1. Write a function that collects form data, verifies the data and return

errors.
function ValidateUser(data)
{
var errors = { } ;
// your validation logic to validate data
return errors;
}

2. Configure validation function with formik


const formik = useFormik( {
initialValues : { },
validate : ValidateUser,
...
})

3. You can display error message by using


[Link]

Ex:

[Link]
import { useFormik } from "formik";

export function FormDemo(){

function ValidateUser(userDetails){
var errors = {UserName:'', Age:'', City:'', Gender: ''};

if([Link]===0){
[Link] = 'User Name Required';
} else {
if([Link]<4){
[Link] = 'Name too short';
} else {
[Link] = '';
}
}

if([Link]===0){
[Link] = 'Age Required';
} else {
if(isNaN([Link])){
[Link] = 'Age must be a number';
} else {
[Link] = '';
}
}

if([Link]==='-1'){
[Link] = 'Please select your city';
} else {
[Link] = '';
}

return errors;
}

const formik = useFormik({


initialValues: {
UserName: '',
Age: 0,
City: '',
Gender: ''
},
validate : ValidateUser,
onSubmit : (user) => {
[Link](user);
}
})

return(
<div className="container-fluid">
<h2>Register User</h2>
<form onSubmit={[Link]}>
<dl>
<dt>User Name</dt>
<dd><input type="text" onChange={[Link]} name="UserName" /></dd>
<dd className="text-danger">{[Link]}</dd>
<dt>Age</dt>
<dd><input type="text" onChange={[Link]} name="Age" /></dd>
<dd className="text-danger">{[Link]}</dd>
<dt>Your City</dt>
<dd>
<select onChange={[Link]} name="City" >
<option value='-1'>Select City</option>
<option value='Delhi'>Delhi</option>
<option value='Hyd'>Hyd</option>
</select>
</dd>
<dd className="text-danger">{[Link]}</dd>
<dt>Choose Gender</dt>
<dd>
<input type="radio" name="Gender" value="Male" onChange={[Link]} /> Male
<input type="radio" name="Gender" value="Female" onChange={[Link]} /> Fe
</dd>
</dl>
<button type="submit">Register</button>
</form>
</div>
)
}
27 January 2026

- Formik

- useFormik()

- Validation
Yup library for Validation

- Yup is a validation services library.

- It comprises of pre-defined validation functions.

- You can customize and implement according to the requirements.

1. Install Yup library for project


> npm install yup --save

2. You can import only the required validation service or all services from

library.
import { required, min, max, ... } from "yup";
(or)
import * as yup from "yup";

3. Validation is defined as a schema by using "[Link]()"


[Link]( {
FieldName: [Link]().required(91message').min().max()..
})

4. You have to configure the schema by using formik "ValidationSchema".


const formik = useFormik({
initialValues: { },
validationSchema: [Link]( { } ),
onSubmit: (values) => { }
})

5. All error messages are defined using "[Link]" object.


{ [Link] }

Ex:

[Link]

import { useFormik } from "formik";


import * as yup from "yup";

export function FormDemo(){

const formik = useFormik({


initialValues: {
UserName: '',
Age: 0,
Mobile: '',
City: '',
Gender: ''
},
validationSchema: [Link]({
UserName: [Link]().required('User Name Required').min(4, 'Name too short'),
Age: [Link]().required('Age Required').min(15, 'Age min 15').max(30, 'Age Max 30'),
Mobile: [Link]().required('Mobile Required').matches(/\+91\d{10}/, 'Invalid Mobile +91 10 di
}) ,
onSubmit : (user) => {
[Link](user);
}
})

return(
<div className="container-fluid">
<h2>Register User</h2>
<form onSubmit={[Link]}>
<dl>
<dt>User Name</dt>
<dd><input type="text" onChange={[Link]} name="UserName" /></dd>
<dd className="text-danger">{[Link]}</dd>
<dt>Age</dt>
<dd><input type="text" onChange={[Link]} name="Age" /></dd>
<dd className="text-danger">{[Link]}</dd>
<dt>Mobile</dt>
<dd><input type="text" onChange={[Link]} name="Mobile" /></dd>
<dd className="text-danger">{[Link]}</dd>
<dt>Your City</dt>
<dd>
<select onChange={[Link]} name="City" >
<option value='-1'>Select City</option>
<option value='Delhi'>Delhi</option>
<option value='Hyd'>Hyd</option>
</select>
</dd>
<dd className="text-danger">{[Link]}</dd>
<dt>Choose Gender</dt>
<dd>
<input type="radio" name="Gender" value="Male" onChange={[Link]} /> Male
<input type="radio" name="Gender" value="Female" onChange={[Link]} /> Fe
</dd>
</dl>
<button type="submit">Register</button>
</form>
</div>
)
}

Validation State

- Every form comprises of 2 levels of validation.

a) Input State

b) Form State

- Input state is the process of verifying every field individually.

- Form State is the process of verifying all fields simultaneously at the same time.
- Formik provides both input and form state validation.

- Formik has pre-defined form state services like


a) touched
b) dirty
c) isValid
d) errors

- touched returns
true

if any form field get focus.

- dirty returns
true

if any form field value is modified. [when user inputs]

- isValid returns
true

if all form fields are valid.

- errors returns a object the comprises of all fields and their error messages.

Syntax:

<button disabled={ ([Link]) ? false: true } > Register </button>

<button disabled={ ([Link]) ? true: false }> Save </button>

- "[Link]" object is used to summarize the form errors.

Syntax:
[Link]([Link]) => returns all error messages [ ].

- Formik provides various events for verifying the form data

a) onChange

b) onBlur

c) onSubmit

- Formik has pre-defined functions for validation events

a) handleChange

b) handleBlur

c) handleSubmit

- You can configure all event handlers individually.

<input type="text" name="UserName" onChange={[Link]}


onBlur={[Link]} />

- You can configure all events handlers using a spread operator.

<input type="text" name="UserName"


{ ...[Link]("UserName") } />

Ex:
import { useFormik } from "formik";

import * as yup from "yup";

export function FormDemo(){

const formik = useFormik({


initialValues: {
UserName: '',
Age: 0,
Mobile: '',
City: '',
Gender: ''
},
validationSchema: [Link]({
UserName: [Link]().required('User Name Required').min(4, 'Name too short'),
Age: [Link]().required('Age Required').min(15, 'Age min 15').max(30, 'Age Max 30'),
Mobile: [Link]().required('Mobile Required').matches(/\+91\d{10}/, 'Invalid Mobile +91 10 di
}) ,
onSubmit : (user) => {
[Link](user);
}
})

return(
<div className="container-fluid">
<h2>Register User</h2>
<form onSubmit={[Link]}>
<dl>
<dt>User Name</dt>
<dd><input type="text" {...[Link]('UserName')} name="UserName" /></dd>
<dd className="text-danger">{[Link]}</dd>
<dt>Age</dt>
<dd><input type="text" onChange={[Link]} name="Age" /></dd>
<dd className="text-danger">{[Link]}</dd>
<dt>Mobile</dt>
<dd><input type="text" onChange={[Link]} name="Mobile" /></dd>
<dd className="text-danger">{[Link]}</dd>
<dt>Your City</dt>
<dd>
<select onChange={[Link]} name="City" >
<option value='-1'>Select City</option>
<option value='Delhi'>Delhi</option>
<option value='Hyd'>Hyd</option>
</select>
</dd>
<dd className="text-danger">{[Link]}</dd>
<dt>Choose Gender</dt>
<dd>
<input type="radio" name="Gender" value="Male" onChange={[Link]} /> Male
<input type="radio" name="Gender" value="Female" onChange={[Link]} /> Fe
</dd>
</dl>
<button type="submit" disabled={([Link])?false:true} className="mx-2">Register</butto
<button className={([Link])?'d-inline':'d-none'}>Save</button>
<div style={{color:'red'}} className={([Link])?'d-none':'d-block'}>
<h3>Please check the following errors in form</h3>
<ul>
{
[Link]([Link]).map(error=> <li key={error}> {error} </li>)
}
</ul>
</div>
</form>
</div>
)
}

Note: Hooks are not allowed in class components. You can't use

"useFormik()" hook for designing and validating a form.

- Formik provides pre-defined components, which allow to design and validate

form without hooks.


<Formik>
<Form>
<Field>
<ErrorMessage>

Reack-Hook-Form

[Link]

28 January 2026

- Formik

- Yup

- Validation

- Validation Schema

- Form State & Input State


isValid
dirty
touched
errors

Formik Components:
<Formik>
<Form>
<Field>
<ErrorMessage>
Syntax:
<Formik initialValues={ } validate={ } validationSchema={ } onSubmit={ }>
<Form>
<Field type="text | email | number | date.." name="FieldName" />
<ErrorMessage name="FieldName" />
</Form>
</Form>
<Form> Formik Form Component
<form> HTML Form

- You can capture the form state and handle form state validations.

Syntax:
<Formik>
{
formik => <Form> </Form>
[Link], dirty, touched etc.
}
</Formik>

Ex:

[Link]

import { Formik, Form, Field, ErrorMessage } from "formik"


import * as yup from "yup";

export function FormikDemo(){


return(
<div className="container-fluid">
<h2>Register User</h2>
<Formik initialValues={{UserName:'', Mobile:''}} validationSchema={[Link]({UserName:[Link]
{
formik =>
<Form>
<dl>
<dt>User Name</dt>
<dd><Field type="text" name="UserName" /></dd>
<dd className="text-danger"><ErrorMessage name="UserName" /></dd>
<dt>Mobile</dt>
<dd><Field type="text" name="Mobile" /></dd>
<dd className="text-danger"><ErrorMessage name="Mobile" /></dd>
</dl>
<button disabled={([Link])?false:true} type="submit">Register</button>
</Form>
}
</Formik>
</div>
)
}

React Hook Form

Features:

1. Performant
- It is light weight as it uses less memory.
- It is modular as it includes only the services required for situation.
- It is faster in rendering output.

2. Flexible & Extensible


- It can adjust according to the requirements.
- It allows extend a form by adding new features without disturbing existing form.
- You can easily add and remove elements from a form.
- A form can change dynamically.

3. Easy to use Validations


- It uses HTML validation attributes.
- It doesn't require a 3rd party validation service.
- Built-in HTML validations are faster in interactions.

Exploring a new Library:

1. Visit the official website of "GIT" repository of library.


[Link]

2. If it is a website then go to API and explore all features provided by library.

If it is a GIT repository go to "[Link]" to explore and know about library.

3. Hook form provides various services like


useForm
useController
useFormContext
useWatch
useFormState etc.

4. Every service is not required for an application. You have to find exactly relative

service for your project.


useForm : for simple form with validations.
useController : for a form in controlled component, where data comes from parent.
useFormContext : for avoiding props drilling, and using context memory.

5. Go to "Get started" to setup and install library for project


> npm install react-hook-form --save

6. Configure a form using "useForm" hook


import { useForm } from "react-hook-form";
const { register, handleSubmit, formState: { errors } } = useForm();
register : It refers to form and its elements.
handleSubmit : It defines actions on submit.
formState : It returns the errors.

7. Create a method for handling submit action.


const submit = (values) => {
[Link](values);
}
<form onSubmit={ handleSubmit(submit) } >
</form>
<input type="text" { ...register("fieldName", { validations }) } />
{ ([Link]?.type==="error-type") ? True : False }

29 January 2026

FAQ: What is Optional Chaining in JavaScript?

Ans: - Javascript is not a strongly typed language.

- It uses dynamic types.

- It verifies the keys at runtime, and if any key not found then it returns errors.

-You can avoid runtime errors and set keys as "undefined" by using "?" Null
reference character.

Syntax:
var product = { name: "TV", rating: { rate : 3.5 } };
[Link]( [Link]); // 3.5
[Link]( [Link]); // undefined
[Link]( [Link]); // rating not defined [vendor] error.
[Link]( [Link]?.rating); // undefined

Ex: [Link]

import { useForm } from "react-hook-form"

export function HookFormDemo(){

const {register, handleSubmit, formState:{errors}} = useForm();

const submit = (user)=> {


[Link](user);
}

return(
<div className="container-fluid">
<form onSubmit={handleSubmit(submit)}>
<h3>Register User</h3>
<dl>
<dt>User Name</dt>
<dd><input type="text" {...register("UserName", {required:true, minLength:4})} name="User
<dd className="text-danger">
{
([Link]?.type==="required")? <span>User Name Required</span> : <span></s
&&
([Link]?.type==="minLength")? <span>Name too short</span> : <span></span
}
</dd>
<dt>Mobile</dt>
<dd>
<input type="text" {...register("Mobile", {required:true, pattern:/\+91\d{10}/})} nam
</dd>
<dd className="text-danger">
{
([Link]?.type==="required")? <span>Mobile Required</span>: <span></span>
&&
([Link]?.type==="pattern")? <span>Invalid Mobile +91 10 digits</span> : <span>
}
</dd>
</dl>
<button type="submit">Submit</button>
</form>
</div>
)
}

Task : Dynamically add or remove elements from form

import { useForm } from "react-hook-form"

export function HookFormDemo(){

const {register, handleSubmit, formState:{errors}} = useForm();

const submit = (user)=> {


[Link](user);
}

return(
<div className="container-fluid">
<form onSubmit={handleSubmit(submit)}>
<h3>Register User</h3>
<dl>
<dt>User Name</dt>
<dd><input type="text" {...register("UserName", {required:true, minLength:4})} name="User
<dd className="text-danger">
{
([Link]?.type==="required")? <span>User Name Required</span> : <span></s
&&
([Link]?.type==="minLength")? <span>Name too short</span> : <span></span
}
</dd>
<dt>Mobile</dt>
<dd>
<input type="text" {...register("Mobile", {required:true, pattern:/\+91\d{10}/})} nam
</dd>
<dd className="text-danger">
{
([Link]?.type==="required")? <span>Mobile Required</span>: <span></span>
&&
([Link]?.type==="pattern")? <span>Invalid Mobile +91 10 digits</span> : <span>
}
</dd>
<dt>Upload Photo</dt>
<dd>
<input type="file" /> <button className="btn d-inline btn-link"> upload more</button>
</dd>
</dl>
<button type="submit">Submit</button>
</form>
</div>
)
}
What's New in React 19x Forms:

1. FormData

- FormData is a browser collection object.

- It can collect the data from any form submitted on POST.

- It is a Key and Value collection.

- Key refers to field name. [element name]

- Value refers to field value. [element value]

- It uses a dynamic memory to store form data.

- Dynamic memory is discrete memory.

- It is not good for continuous operations.

Syntax:
let formdata = new FormData(formReference);
function handleSubmit(e)
{
let formdata = new FormData([Link]); // sends form reference.
[Link](key)
[Link](key)
[Link](key)
.keys()
.values()
.entries()
etc..
}

Ex: [Link]

export function NewFormDemo(){

function handleSubmit(e){
[Link]();
let formdata = new FormData([Link]);
[Link](`User Name : ${[Link]('UserName')}\nMobile : ${[Link]('Mobile')}`);
}

return(
<div className="container-fluid p-3">
<form onSubmit={handleSubmit}>
<dl>
<dt>Name</dt>
<dd><input type="text" name="UserName" /></dd>
<dt>Mobile</dt>
<dd><input type="text" name="Mobile" /></dd>
</dl>
<button type="submit">Submit</button>
</form>
</div>
)
}

2. useRef

- It is a react hook.

- It is used to configure a reference memory.

- Reference memory is intended to used with in the context of process.

- It is good for values used inside process but not for rendering in UI.

- It configure a thread in current process and stores the value of element.

- Every HTML form element can be configured with "ref" property, which maps to

reference memory.

Syntax:
const nameRef = useRef(null);
<input type="text" name="UserName" ref={ nameRef } />

- You can access with reference of current thread.

Syntax:
[Link] // refers to entire form element <input>
[Link] // refers to input value

3. useFormState()

4. useFormAction()

- These are new React 19 hooks for handling server side actions.
- A client component can collect data from form and submit to any server
component

using the new hooks.


React Routing

30 January 2026

- Web technologies use various techniques to handle different functionalities.

- Some of the popular techniques include

a) Data Binding
b) Event Binding

c) State Management

d) Caching

e) Model Binding

f) Routing etc.

- Routing is a technique used in web applications to configure user and SEO


friendly URL's.

- User friendly URL's allow user to query any content directly from address bar.

Ex: without route

[Link]
=apple

Ex: with route

[Link]

- SEO friendly URL allows web crawlers to find the exact location of user in page.
- Routing implicitly uses AJAX, which allows to load new content into page without reloading the page.

- In SPA [Single Page Application] user can stay on one page and can access
everything

on to the page.

- Routing can be configured


a) Server Side

b) Client Side

- Server Side routing is used in server frameworks, it can be in server side app or
API.

- Client side libraries and frameworks can use routing for navigation.

- React library doesn't provide any routing support implicitly.

- You have to enable routing by using the routing library "react-router-dom".

- The latest router-dom version is "7".

1. Install React Router DOM for project

> npm install react-router-dom --save

2. React router provides following components


<BrowserRouter>

<Routes>

<Route>

<Link>

<Outlet>

- BrowserRouter : It is responsible for converting the virtual DOM routes into


actual DOM.

In actual DOM the navigation is managed by location object. [BOM]

- Routes : It is used to configure the route table. It is a collection of routes.

- Route : It is used to configure every individual route in a routes collection.

- Link : It creates anchor used for route navigation.

- Outlet : It is used to configure the target location for child routes.

Syntax:
<BrowserRouter>
<Routes>
<Route path={ } element={ } children={ } />
</Routes>
</BrowserRouter>

Ex:

[Link]
import { BrowserRouter, Route, Routes, Link } from "react-router-dom";

import { TutorialHome } from "./tutorial-home";


import { JavaTutorial } from "./java-tutorial";
import { ReactTutorial } from "./react-tutorial";
import { WeatherApp } from "../components/weather-app/weather-app";

export function TutorialIndex(){


return(
<div className="container-fluid">
<BrowserRouter>
<header>
<h2 className="text-center">Tutorial Index</h2>
<nav>
<span><Link to="/home">Home</Link></span>
<span className="mx-5"><Link to="/java">Java Tutorial</Link></span>
<span className="me-5"><Link to="/react">React Tutorial</Link></span>
<span><Link to="/weather">Weather</Link></span>
</nav>
</header>
<hr />
<section>
<Routes>
<Route path="home" element={<TutorialHome />} />
<Route path="java" element={<JavaTutorial />} />
<Route path="react" element={<ReactTutorial />} />
<Route path="weather" element={<WeatherApp />} />
</Routes>
</section>
</BrowserRouter>
</div>
)
}

31 January 2026

<BrowserRouter>

<Routes>

<Route>

<Link>

Route Path:

- It refers to client request for any specific component.


<Route path="request" />

- You can configure Wild Card routes.


a) " / " It refers to the client request, if is not for any specific path.
It can be considered as default route.
b) " * " It renders content when the request path not found.
- Route path refers to "element", which can be a component or any dynamically generated JSX fragment.
Syntax:
<Route path=" / " element={ <Component /> } />
<Route path=" * " element={ <div> any fragment </div> } />

Route Parameters:

- Route parameter is appended into the current route path.

- It is used to query any content directly in the current context.

- It is also used to transport data from one component to another.

- Parameter is configured in route path by using " /: "

- You can configure multiple parameters.

Syntax:
<Route path="products/:category/:product/:rating" element={ <Component /> } />

- The values into parameters are defined from URL


[Link]
category = electronics
product = mobile
rating = 4

- You can access the route parameters by using the hook "useParams()".

- It is a hook of "react-router-dom" library.

- It returns an object with key and value collection.


Syntax:
let params = useParams(); // { key : value }
[Link]
[Link]
[Link]

- Every parameter is a required parameter. It is mandatory to configure a value for

every parameter in route path.

Ex:

1. [Link]
import { BrowserRouter, Route, Routes } from "react-router-dom";

import { FakestoreHome } from "./fakestore-home";


import { FakestoreProducts } from "./fakestore-products";
import { FakestoreDetails } from "./fakestore-details";

export function FakestoreIndex(){


return(
<div className="container-fluid">
<BrowserRouter>
<header className="bg-dark text-white text-center p-2">
<h1> <span className="bi bi-bag"> Shopping </span> </h1>
</header>
<section>
<Routes>
<Route path="/" element={<FakestoreHome />} />
<Route path="/products/:category" element={<FakestoreProducts />} />
<Route path="/details/:id" element={<FakestoreDetails />} />
</Routes>
</section>
</BrowserRouter>
</div>
)
}

2. [Link]

import axios from "axios";


import { useEffect, useState } from "react"
import { Link } from "react-router-dom";

export function FakestoreHome(){

const [categories, setCategories] = useState([]);


function LoadCategories(){
[Link](`[Link]
.then(response=>{
setCategories([Link]);
})
}

useEffect(()=>{

LoadCategories();

},[])

return(
<div className="container-fluid mt-5">
<h4>Shopping Home</h4>
<ul className="list-group w-25">
{
[Link](category=>
<li className="list-group-item my-2 list-group-item-secondary" key={category}> <span>
)
}
</ul>
</div>
)
}

3. [Link]
import axios from "axios";

import { useEffect, useState } from "react";


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

export function FakestoreProducts(){

let params = useParams();

const [products, setProducts] = useState([{id:0,title:null, price:0, image:null, description:null, catego

function LoadProducts(){
[Link](`[Link]
.then(response=>{
setProducts([Link](product=> [Link]===[Link]));
})
}

useEffect(()=>{
LoadProducts();
},[])

return(
<div className="container-fluid mt-4">
<h4>Products</h4>
<div className="d-flex flex-wrap flex-row" style={{width:'600px'}}>
{
[Link](product=>
<div className="card m-2 p-2" style={{width:'130px'}} key={[Link]}>
<div className="card-header">
<img className="card-img-top" src={[Link]} height="50" />
</div>
<div className="card-footer">
<Link to={`/details/${[Link]}`} className="btn btn-dark w-100" > Details </Link>
</div>
</div>
)
}
</div>
<Link to="/">Back to Categories</Link>
</div>
)
}

4. [Link]

import { Link, useParams } from "react-router-dom"


import { useEffect, useState } from "react";
import axios from "axios";

export function FakestoreDetails(){

let params = useParams();


const [product, setProduct] = useState({id:0,title:null, price:0, image:null, description:null, category:

function LoadProduct(){
[Link](`[Link]
.then(response=>{
setProduct([Link]);
})
}

useEffect(()=>{
LoadProduct();
},[])

return(
<div className="container-fluid mt-4">
<h4>Details</h4>
<dl>
<dt>Title</dt>
<dd>{[Link]}</dd>
<dt>Preview</dt>
<dd>
<img src={[Link]} width="200" height="200" />
</dd>
<dt>Price</dt>
<dd>{[Link]('en-us', {style:'currency', currency:'USD'})}</dd>
</dl>
<Link to={`/products/${[Link]}`}>Back to Products</Link>
</div>
)
}

02 February 2026

Route Parameters

Child Routes:

- A <Route> component can use nested routes.


- It renders a component with in the context of same route.

Syntax:
<Route path="parent" element={ <Parent /> } >
<Route path="child" element= { <Child /> } />
... multiple child routes ...
</Route>
</Route>

FAQ: What is difference between absolute and relative routes? [Path]

Ans: Absolute route refers to individual path. It can access and render component

individually.
[Link]
<Route path="details" ... />
<Link to="details"> Details </Link> Relative
[Link]
<Link to="/details"> Details </Link> Absolute
[Link]
Relative route refers to a path that is accessed with in the context of current.
It can referred as child route.

FAQ: What is <Outlet> ?

Ans : It refers to the target location where the resulting markup is rendered.
The child route target [element] is rendered at outlet position.

FAQ: Can we configure multiple route outlets?

Ans: Yes. You can render child content at multiple locations.

FAQ: What are search parameters?

Ans:
- HTML form can submit data on GET and POST requests.
- Data will be in FormData when you submit on POST request.
- Data will be in Query String when you submit on GET request. - Query String in React can be appended to
Route path as a key and value
collection.
Syntax:
[Link] ? Key = value & key = value
- React can access the search parameters by using useSearchParams() hook.
- In Actual DOM you can access query string using "[Link]" and convert
into parameters collection using URLSearchParams().
Syntax:
let [params] = useSearchParams();
[Link]( key );
To-DO Application
04 February 2026

- MUI is a component library for building interactive and responsive UI.

- It is built for React.

- MUI provides various products like

a) MUI-Core

b) MUI-X

c) Templates

d) Design Kits

- MUI-Core is a free component library for React applications.

1. Install MUI for project


> npm install @mui/material @emotion/react @emotion/styled --save

2. Import the required component from library


import Button from "@mui/material/button";
(or)
import { TextField, Button } from "@mui/material";

3. Every component is provided as controlled component, it comprises of "props".


<Button type="submit" color="primary" variant="contained"> Text </Button>
<TextField type="text | password | number.." name="Name" variant="standard" />

4. Events for components are same as you defined for JSX components.

[Synthetic Events]
<TextField onChange={ handleChange } />
<Button onClick= {handleClick } />

Ex:

[Link]

import { TextField, Button } from "@mui/material";


import { useFormik } from "formik";

export function MuiDemo(){

const formik = useFormik({


initialValues: {
UserName: '',
Password:''
},
onSubmit : (userdata)=> {
[Link](userdata);
}
})

return(
<div className="container-fluid">
<div className="mt-2 row">
<div className="col">
<h3>Bootstrap Login</h3>
<form className="w-50">
<div className="mb-2">
<label className="form-label">User Name</label>
<div>
<input type="text" className="form-control" />
</div>
</div>
<div className="mb-2">
<label className="form-label">Password</label>
<div>
<input type="password" className="form-control" />
</div>
</div>
<div>
<button className="btn btn-primary w-100">Login</button>
</div>
</form>
</div>
<div className="col">
<h3>MUI Login</h3>
<form className="w-50" onSubmit={[Link]}>
<div className="mb-2">
<TextField onChange={[Link]} name="UserName" className="w-100" type
</div>
<div className="mb-2">
<TextField onChange={[Link]} name="Password" className="w-100" type
</div>
<div>
<Button type="submit" className="w-100" variant="contained" color="primary"> Logi
</div>
</form>
</div>
</div>
</div>
)
}

TO-DO Application

- To-do is a simple scheduler used to organize appointments.

- User can register into application.

- User can login

- User views the dashboard with all scheduled appointments after login.

- Login credentials are managed with cookies. User session is maintained with
cookie.

- User can manage appointments from dashboard

a) Add

b) Edit
c) Delete

Database Models: [Logical Model]

Users
UserId [PK]
UserName
Password
Email

Appointments
Title
Description
Date
Id [PK]
UserId [FK]
[Physical Model]

Users

UserId [string]

UserName [string]

Password [string]

Email [string]

Appointments

Id [number]

Title [string]
Description [string]

Date [date]

UserId [string]

API & Data

- You can use a local JSON-SERVER.

- It stores your data in ".json" file.

- Data is locally kept in your project folder.

- It creates API end points to manage the data in JSON file.


GET for fetching
POST for saving
PUT for updating
DELETE for deleting
1. Install JSON-SERVER for project
> npm install json-server --save

2. Create a new file by name "[Link]" and add into project root folder.
{
"users": [ ],
"appointments: [ ]
}

3. Start the API from terminal


>npx json-server [Link] --watch
End Points:
GET [Link]
[Link]

Note: Make sure that every record has an "id" in JSON data.

05 February 2026

Set API in start up to run via command:

1. Go to [Link] file

2. Set the following command with alias at "scripts".


"scripts": {
....,

"api" : "npx json-server [Link] --watch"


}

3. Every time you can run the following command from terminal
> npm run api

API Routes for To-Do App: [ [Link] ]

GET /users

GET /appointments

GET /users/id ] It is auto generated and string type

GET /appointments/id ]

POST /users

POST /appointments

PUT /users/id

PUT /appointments/id
DELETE /users/id

DELETE /appointments/id

Dynamic Route Navigation:

- It is the process of navigating user from one route to another according to the
state

and situation.

- The latest router-dom library provides "useNavigate()" hook, which allows


dynamic

navigation.

Syntax:
let navigate = useNavigate();
navigate("/path");

06 February 2026

Handling User State [Login to Logout]

- There are various client side state management techniques, which we can use to

manage the user state.

a) Query String
b) Local Storage

c) Session Storage

d) Cookies

- The best state management technique for login is Cookies.

- Cookies can be

a) In memory : Temporary

b) Persistent : Permanent

- In actual DOM cookie is managed by using "document" object.

- React requires a 3rd party library to manage cookies with virtual DOM.

1. Install React Cookie Library

> npm install react-cookie --save


2. Go to "[Link]" and configure cookie provider

import { CookiesProvider } from 91react-cookie';

<CookiesProvider>
<ToDoIndex />

</CookiesProvider>

- Provider is a service object.

- It is responsible for locating the value in memory and inject into component.

3. Cookies can be configured in any component by using "useCookies()" hook

import { useCookies } from 91react-cookie';

const [cookies, setCookie, removeCookie] = useCookies([ 91name', 91name' ]);

cookies : It is a getter used to access cookie value.

setCookie : It is a setter used to create a new cookie.

removeCookie : It is used to remove cookie explicitly from memory.

Syntax:
cookies[ 91name' ] // returns the cookie value
setCookie( 91name', 91value', { expires: date } );
removeCookie(91name');

07 February 2026

HYPERLINK "[Link]
hGroup/react-demo-app-6pm-2026

09 February 2026

Edit Action - ToDo App

- Fetch the details of appointment using "id" which is a route parameter.

[Link](`[Link]

- Initialize the values in formik

useFormik( {
initialValues : {
id: [Link],
title: [Link],
}

})

- Initialization of data into formik is default disabled. You have enable initialization.

useFormik( {
initialValues: { },
onSubmit: () => { },
enableReinitialize : true

})

- Submit action must use "put()" method for updating the details
onSubmit : ( appointment ) => {
[Link]( `[Link] appointment );
}

- Bind initial value to elements in form

<input type="text" name="title" value={ [Link] } />


React Component Life Cycle

10 February 2026

- Creation

- Mount

- Update

- Unmount

Lazy & Suspense Features

- Lazy loading is the mechanism of loading only the content required for situation.

- React loads all Javascript modules as bundle at the time of initializing


application.

- It is heavy on application.
- You can enable lazy loading, so that it loads only the chunk of JS bundle that is

required for request.

- React provides lazy & suspense components for importing library.

- Suspense is the state after request and before load.

Syntax: Eager Loading

import { component } from "./path";


Lazy Loading

import { lazy } from "react";

const component = lazy( ( ) => import( "./path") );

<Suspense fallback={ <div> Loading please wait... </div> } >


<component />

</Suspense>

Note: Make sure that the component loaded with lazy technique is a
default component.

Syntax:
export default function Component() { } => can load lazy
export function Component() { } => can't load lazy

Ex: [Link]

import { lazy, Suspense } from "react";


import { BrowserRouter, Link, Route, Routes } from "react-router-dom";
import { ToDoHome } from "./todo-home";
import { ToDoLogin } from "./todo-login";
import { ToDoRegister } from "./todo-register";
import { ToDoAdd } from "./todo-add";
import { ToDoDelete } from "./todo-delete";
import { ToDoEdit } from "./todo-edit";
import { ToDoDetails } from "./todo-details";
const ToDoDashboard = lazy(()=> import('./todo-dashboard'));

export function ToDoIndex(){


return(
<div className="container-fluid">
<BrowserRouter>
<header className="p-3 m-1 bg-light d-flex justify-content-between">
<div>
<span className="bi fs-4 mx-2 bi-pencil-square"></span>
<span className="fs-4 fw-bold"> <Link to="/" className="text-secondary text-decoration-no
</div>
<div>
<button className="btn me-2">Features</button>
<button className="btn">Pricing</button>
<button className="btn mx-2">About</button>
<button className="btn btn-primary">Get Started</button>
</div>
</header>
<section className="mt-2">
<Suspense fallback={<div>Loading component please wait..</div>}>
<Routes>
<Route path="/" element={<ToDoHome />} />
<Route path="login" element={<ToDoLogin width='w-25' />} />
<Route path="register" element={<ToDoRegister width='w-25' />} />
<Route path="dashboard" element={<ToDoDashboard />} >
<Route path="" element={<ToDoDetails />} />
<Route path="details" element={<ToDoDetails />} />
<Route path="add" element={<ToDoAdd />} />
<Route path="edit/:id" element={<ToDoEdit />} />
<Route path="delete/:id" element={<ToDoDelete />} />
</Route>
</Routes>
</Suspense>
</section>
</BrowserRouter>
</div>
)
}

React Hooks

- Hook is a service of React.

- Service is a pre-defined business logic used to implement and customize any

functionality in application.

- It enables features like

a) Reusability

b) Extensibility

c) Maintainability

d) Testability etc.
- React has several pre-defined services and allows to create custom services.

- Service is used in any component with DI [Dependency Injection]

- Service comprises of

a) consumer

b) provider

c) subscriber

d) injector etc.

- Consumer uses the service.

- Provider is responsible for locating and injecting the services into components.

Custom Hooks:
11 February 2026

- What is Service?

- Values / Functions => Factory => Service => Component

- Consumer, Provider, Injector, Subscriber

- DI
Custom Hooks

- Hook is a function.

- Hook function name must start with "use" and must be in camelCase.
function useCaptcha()
{
}

- Hook function can't be void type. It must return a value or function.


function useCaptcha()
{
return value / function(){ }
}

- It can parameter less or parameterized.

- If it is parameterized then it is mandatory to pass relative arguments.


function useCaptcha(code)
{
return value;
}

- You can't access and use a hook inside any block, you can use only in React

component block or custom hook block.


if (condition)
{
const [user, setUser] = useState(91name'); // invalid
}
function Component() => component
{
const [user, setUser] = useState(); // valid
}
function handleSubmit()
{
const [user, setUser] = useState(); // invalid
}
function useCaptcha() => Hook
{
const [user, setUser] = useState(); // valid
}
- It is mandatory to call a hook with exactly specified arguments.

- It must match with argument data type and order.

- A custom hook can use all React built-in hooks.

FAQ: Why to use a hook, if the same can be achieved using function?

Ans: Normal function is always accessed using Single Call.


Hook function is accessed using Single ton.

FAQ: What are Single Call & Single Ton?

Ans: Single Call is a design pattern used to create an object for every request.
Single Ton is a pattern where object is created for first request and the same
is used across requests.

Ex:

1. Src/hooks/[Link]

export function useCaptcha(){


let code = '';
code = `${[Link]([Link]()*10)} ${[Link]([Link]()*10)} ${[Link]([Link]()*10)} $
return code;
}

2. [Link]
import axios from "axios";

import { useFormik } from "formik";


import { useEffect, useState } from "react";
import { Link, useNavigate } from "react-router-dom";
import { useCookies } from "react-cookie";
import { useCaptcha } from "../hooks/use-captcha";

export function ToDoLogin(props){

const [users, setUsers] = useState([{user_id:null, user_name:null, password:null, email:null}]);


let navigate = useNavigate();
let code = useCaptcha();

const [cookies, setCookie, removeCookie] = useCookies(['userid','username']);

function LoadUsers(){
axios('[Link]
.then(response=>{
setUsers([Link]);
})
}

useEffect(()=>{
LoadUsers();
},[])

const formik = useFormik({


initialValues : {
user_id : '',
user_name: '',
password: '',
email:''
},
onSubmit: (user)=>{
var userDetails = [Link](item=> item.user_id===user.user_id);
if(userDetails)
{
if([Link]===[Link]){
setCookie('userid', userDetails.user_id);
setCookie('username', userDetails.user_name);
navigate('/dashboard');
} else {
alert('Invalid Password');
}
} else{
alert('Invalid User Id');
}
}
})

return(
<div className="container-fluid">
<form onSubmit={[Link]} className={`p-4 ${[Link]}`}>
<h4 className="bi bi-person-fill"> User Login</h4>
<dl>
<dt>User Id</dt>
<dd><input type="text" onChange={[Link]} name="user_id" className="form-cont
<dt>Password</dt>
<dd><input type="password" onChange={[Link]} name="password" className="form
<dt>Verify Code</dt>
<dd>{code}</dd>
</dl>
<button type="submit" className="btn btn-primary w-100">Login</button>
<div className="mt-4">
<Link to="/register">New User Register</Link>
</div>
</form>
</div>
)
}

- Every custom hook can have the phases like mount and unmount.

- Hook mount is executed while loading and unmount, while changing hook.

Ex: src/hooks/[Link]

import axios from "axios";

import { useEffect, useState } from "react";

export function useFetchData(url){


const [data, setData] = useState([]);

useEffect(()=>{
[Link](url)
.then(response=> setData([Link]));
},[url])

return data;
}

[Link]
import { useFetchData } from "../hooks/use-fetchdata";

const appointments = useFetchData('[Link]

<ul>

{[Link](appointment=><li key={[Link]}>{[Link]}</li>)}
</ul>

React Built-In Hooks

12 February 2026

1. useEffect()

- It defines actions to perform while mounting & unmounting component.

- Component mounts after creation of component object.

- Component unmounts when user navigates to another component.

Syntax:
useEffect( ( )=> {
// actions on mount
return ()=> {
// actions on unmount
}
},[dependencies])

- Typically the mount actions include


a) Initialization of state with new values
b) Loading API data
c) Executing functions to get ready on mount etc.

- Typically the unmount actions include


a) Disconnecting the subscribed methods
b) Removing event listeners c) Reset the initialized values
d) Clean up the memory etc.

- A component mounts only once, you can configure the dependencies to

re-mount the component. It mounts again when the dependency changes.

Ex: [Link]

import { useEffect, useState } from "react"


export function Login(){

useEffect(()=>{
[Link]('Login Mounted');
return()=>{
[Link]('Login Unmounted');
}
},[])
return(
<div>
<h3>Login</h3>
</div>
)
}
export function Register(){

useEffect(()=>{
[Link]('Register Mounted');
return()=>{
[Link]('Register Unmounted');
}
},[])
return(
<div>
<h3>Register</h3>
</div>
)
}

export function EffectDemo(){

const [view, setView] = useState('');

function handleLoginClick(){
setView(<Login />);
}

function handleRegisterClick(){
setView(<Register />);
}

return(
<div className="container-fluid">
<div className="p-5">
<button onClick={handleLoginClick}>Login</button>
<button onClick={handleRegisterClick}>Register</button>
<hr />
{view}
</div>
</div>
)
}

FAQ's:
1. Can we define multiple mount phases for a component?
A. Yes. You can define multiple useEffects() in a component.
2. Why we need multiple useEffects() in a component?
A. To render and define various actions on mount.
You can conditionally mount different actions for a component.

2. useState()
- It uses the component local state created for component.

- It is mutable and accessible across requests in a component.

- It is not accessible to child components.

- It is destroyed when component navigates to another component.

- It is a memory that can handle any type of data.

Syntax:
const [ get, set ] = useState( value );

- State uses a getter to read and return value.

- It uses a setter to re-initialize a new value.

FAQ's: Refer to your previous notes

3. useContext()

- It uses context memory created for a component.

- It is a solution for Props drilling.

- It makes the memory of a component accessible to its child components at

any level of hierarchy.

Syntax:
let ContextName = createContext(null);
let context = useContext(ContextName);
<ContextName value={ data } >
... context scope .. for child components ...
</ContextName>

- You can carry data from child to parent by using Custom Events.

4. useRef()

- It configures a reference memory.

- It is intended to use in a background process.

- It can store value and provide without re-render.

Syntax:
let thread = useRef(null);
[Link] = value / function;

5. useMemo()

- It allocates a memory to store data.


- Memory is a cache updated only when any dependency changes.

- It provides data across multiple requests without re-rendering.

- It avoids round trips.

- Round trip is the process of requesting content every time from server.

Syntax:
useMemo( ()=>{
return data;
},[dependencies])
var data = useMemo( ()=> { return data }, [ dependencies ]);
[Link]().filter().sort() etc..

6. useCallback()

- It is same as useMemo().

- Memo can memoized the data and keep cache.

- Callback can keep a function in memory.

- You can execute function without re-render.

- It can update when dependency changes.

Syntax:
useCallback(()=>{ }, [ dependency ])
const LoginClick = useCallBack( ()=>{
setCookie();
other actions on login..
},[cookies])
<button onClick={ LoginClick } > Login </button>

7. useReducer

13 February 2026

1. useEffect

2. useState

3. useRef

4. useContext

5. useMemo

6. useCallback
7. useOutletContext [react-router-dom]

Changes in To-Do Application:

1. Go to [Link]

previous:
function LoadAppointments() { }

new:
const LoadAppointments = useCallback(()=>{
// axios to load all appointments.
},[])
useEffect(()=>{
LoadAppointments();
},[])

previous : Load appointments is filtering user details, remove filter and load
all appointments.

new:
const userAppointments = useMemo(()=>{
return [Link]();
},[appointments, cookies])
- Load userAppointments in table.
[Link]( appointment=> <tr> </tr> )

2. Go to [Link]

const handleSignout = useCallback(()=>{


// signout logic

},[cookies])

Filtering Todo-Appointments by Title:


1. Todo-dashboard has a search box, you can access data from search box and store as search string
const [ searchString, setSearchString] = useState(91 ');
<input type="text" onChange={ (e)=> setSearchString([Link]) } />

2. Todo-dashboard is a parent route with outlet, Every route outlet has a default
context
<Outlet context={ {searchString} } />

3. Go to "[Link]" and import outlet context


import { useOutletContext } from "react-router-dom";
const { searchstring } = useOutletContext()

4. Change the logic in userAppointments filter


const userAppointments = useMemo(()=>{
if(searchstring===91 ') {
// filter and return all
} else{
// filter and return the appointments that match title
}
},[])

8. useLayoutEffect()

- useEffect hook executes after the Paint phase.

- useLayoutEffect executes after Layout Render and Before Paint.

- It is good for handling UI layout related interactions.

Syntax:

useLayoutEffect(()=>{
// styles to control layout

},[dependencies])

9. useInsertionEffect()

- It executes before layout

- It is used to plugin external Javascript libraries into component.

- MUI uses emotion, moment uses date & time etc.

Syntax:

useInsertionEffect(()=>{
// inject libraries for component

},[])

10. useReducer

14 February 2026

- It uses application state.


- Application state is a global state that starts on application start and ends on
application end.
- It can keep the data and make it available across multiple sessions.
- Reducer uses global state and handle communication with components.
- It comprises of the following
a) Store
b) State
c) Reducer
-
Store
is the location where data is kept. It is global in access.
-

State
is responsible for accessing data from store and providing to component UI.
-

Reducer
identifies the actions [trigger] in UI and update data into store.

- Dispatch
is responsible for sending the data from component to store.

1. Configure initialState which refers to store.


let initialState = { data }

2. Configure reducer, which is a function that handles state and actions


function reducer(state, action)
{
switch([Link])
{
case "type1":
update state;
case "type2":
update state;
}
}

3. You can use reducer in any component.


- reducer contains state and actions.
let [state, dispatch] = useReducer(reducer, initialState)
dispatch({ type: 91type1' }); // sending update data to store
[Link]; // accessing data from store
Ex: [Link]

import { useReducer } from "react"

let initialState = {
likes: 0
}

function reducer(state, action){


switch([Link]){
case "like":
return { likes: [Link] + 1 }
case "dislike":
return { likes: [Link] - 1 }
}
}

export function ReducerDemo(){


const [state, dispatch] = useReducer(reducer, initialState);
function handleLikeClick(){
dispatch({type: 'like'});
}

return(
<div className="container-fluid">
<div className="mt-4 w-50 card">
<div className="card-header">
<h2>Naresh IT Live</h2>
</div>
<div className="card-body">
<iframe src="[Link] className="w-100" height="300"></
</div>
<div className="card-footer">
<button onClick={handleLikeClick} className="btn btn-warning bi bi-hand-thumbs-up"> [{sta
</div>
</div>
</div>
)
}

Issues with Global State:


- Global application state is not predictable.
- It is difficult for developers to track and identify the changes in data.
- It is not easy to debug.
- Browser or Client developer tools are not enough to debug the global application
state.
- It is not easy to maintain and test global state.

Redux JS
- It is a Javascript library for global application state management.
- It provides a toolkit for developers.
- Toolkit is a tool chain that provides features for building, debugging and testing
application state.
- It provides complete environment for enterprise based applications.
- It provides 2 libraries
a) Redux Core
b) Redux Toolkit
- Redux Core is a minimal library with reducers and not recommended for large scale
applications.
- Redux Toolkit is professional with all features from design to test.

16 February 2026

Redux Toolkit Configuration:

1. Install Redux JS and enable for React

> npm install @reduxjs/toolkit react-redux --save

2. Add a new slicer to project


src/slicers/[Link]

- Slicer configures initial state, which defines the data to handle in application

memory.

- It also configures reducer, which defines the actions to perform and the

state to update data.

- Toolkit provides a method called createSlice() for configuring slicer.

Syntax:
const SlicerName = createSlice({
name : "SlicerName",
initialState,
reducer: {
action1: (state, action) => { [Link] },
action2: (state, action) => { [Link] }
}
})
export const { action1, action2 } = [Link];
export default [Link];

- In [Link] you have to define initial state, which specifies the data.
let initialState = { };

3. Create a store

src/store/[Link]

- It is global storage.
- It stores your data in application memory and provides to all sessions in

application.

- Store gets data from reducer.

- You can create store by using the toolkit method createStore().


configureStore() : It is the used in previous versions. [deprecated]
createStore() : It is recommended for latest versions.

Syntax:
export default createStore()
{
reducer: { SlicerName }
}

4. Enable application state configuration on application start.


src/[Link]

- Store is a service.
- It uses a provider.

- Provider locates data in memory and injects into component.

- Components in provider scope can access the data.

<Provider store={ store }>


<App />

</Provider>

5. Updating data into store from component UI

- React redux provides useDispatch() method.

- Import actions from reducer [slicer] and dispatch the payload into store.

Syntax:

let dispatch = useDispatch();

dispatch(action(data)); // on any event in component

Note : To track and debug Redux install the extension for your browser
"Redux DevTools".

6. You can access and use store from component by using store reference
import store from "../store/[Link]";
[Link]().your_data

17 February 2026

Slicer
createSlice()
Store
configureStore / createStore
Reducers
useDispatch()
Redux DevTools
useOptimistic()
useActionState()
useFormState()

React Class Components


- Class is a program template.
- Class in JS is configured using 2 techniques
a) Class Declaration
class Name
{
}
b) Class Expression
const Name = class {
}
- Class Members
a) Property
b) Method
c) Accessor
d) Constructor
- Static Members
- Prefixes
_ internal
# private
- Inheritance
- Polymorphism
- "this" keyword

Issues with OOP


- They will not support low level features.
- They can't directly interact with hardware services.
- They use more memory.
- They are tedious.

Class Components:
1. A class component must extend

a) [Link]
(or)

b) [Link]
Syntax:
export class Name extends [Link] (or) [Link]
{
}
-

PureComponent
avoids re-renders.
2. Call the super constructor in derived class
export class Name extends [Link]
{
constructor() {
super();
}
}
3. It must return JSX element by using

render()
method.
export class Name extends [Link]
{
constructor() {
super();
}
render() {
return(
< > JSX </>
)
}
}

State in Class Component:


- State is built-in for class component.
- You have to configure state while creating component [in constructor]
Syntax:
constructor() {
[Link] = { }
}
- State is object type with key and value collection.
- You can set state by using "

[Link]()
" method.
- You can access state by using

"[Link]".

Component Life Cycle Methods


a) componentDidMount()
b) componentWillMount()
c) componentWillUnmount()
d) componentDidUpdate()
Ex: [Link]

import React from "react";

export class UserLogin extends [Link]


{
constructor(){
super();
[Link] = {
title: 'User Login',
categories: ['All','Fashion', 'Electronics']
}
}
componentDidMount(){
[Link]({title: 'Customer Login'});
}
render(){
return(
<div className="container mt-3">
<h2>{[Link]}</h2>
<ol>
{
[Link](category=><li key={category}>{category}</li>)
}
</ol>
</div>
)
}
}

Event Binding in Class Components:


1. Event in class maps to a method.
handleClick(e)
{
}
<button onClick={ [Link] } >
2. All Synthetic Events library is same
3. It is mandatory to bind the event handlers with current class memory if they are
using state.
Syntax:
constructor()
{
super();
[Link] = { }
[Link] = [Link](this);
}
Ex:

import React from "react";

export class UserLogin extends [Link]


{
constructor(){
super();
[Link] = {
msg: ''
}
[Link] = [Link](this);
}

handleInsertClick(){
[Link]({msg: 'Record Inserted'});
}

render(){
return(
<div className="container mt-3">
<h2>Class Component</h2>
<button onClick={[Link]} >Insert</button>
<p>{[Link]}</p>
</div>
)
}
}

18 February 2026
- State

- Event Binding

- Life Cycle Hook Methods

2. You can bind in event handler

<button onClick= { [Link](this) } >

3. Without using bind method

<button onClick= { ()=> [Link]() } >

Ex:

import React from "react";

export class UserLogin extends [Link]


{
constructor(){
super();
[Link] = {
msg: ''
}
[Link] = [Link](this);
}

handleInsertClick(){
[Link]({msg: 'Record Inserted'});
}
handleUpdateClick(){
[Link]({msg: 'Record Updated'});
}

render(){
return(
<div className="container mt-3">
<h2>Class Component</h2>
<button onClick={[Link]} >Insert</button>
<button onClick={()=> [Link]()}>Update</button>
<p>{[Link]}</p>
</div>
)
}
}

Forms in Class Component:

- You can't use a library with hooks.

- Formik provides built-in components like

<Formik>

<Form>

<Field>
<ErrorMessage>

- Class components can use built-in Formik components with validation schema

library like Yup.

Syntax:
<Formik initialValues={ } validationSchema={ } onSubmit={ }>
<Form>
<Field>
<ErrorMessage>
</Form>
</Formik>

Controlled Class Components

- Every class component has built-in Props.

- You can configure dynamic keys with values.

Syntax:

export class Name extends [Link]


{
...
...
render(){
return ( <div> { [Link] } </div> )
}
}

Ex:

controlled-components/[Link]

import React from "react";

export class Toolbar extends [Link]


{
constructor(){
super();
}
render(){
return(
<nav className="container-fluid d-flex justify-content-between align-items-center m-2 p-4 border
<div>
<span className="fs-3 fw-bold">{[Link]}</span>
</div>
<div>
{
[Link](item=><span key={item} className="mx-4">{item}</span>)
}
</div>
<div>
<span className="bi bi-person-fill"></span>
</div>
</nav>
)
}
}

[Link]

import React from "react";


import { Toolbar } from "../controlled-components/toolbar";

export class UserLogin extends [Link]


{
constructor(){
super();
[Link] = {
msg: ''
}
[Link] = [Link](this);
}

handleInsertClick(){
[Link]({msg: 'Record Inserted'});
}
handleUpdateClick(){
[Link]({msg: 'Record Updated'});
}

render(){
return(
<div className="container mt-3">
<Toolbar brand='Amazon' items={['Home','Shop','Offers']} />
<h2>Class Component</h2>
<button onClick={[Link]} >Insert</button>
<button onClick={()=> [Link]()}>Update</button>
<p>{[Link]}</p>
</div>
)
}
}

FAQ: Can we access a function component in class component & vice versa?

Ans: Yes. Class can have a function, but it can be a class member.

Syntax:
class Demo
{
function f1() { } // invalid
}
class Demo
{
print() {
function f1(){ } // valid
}
}

Note: Component Life Cycle Hooks are different from React Hooks?
- Life Cycle Hooks [Classes]
componentWillMount()
componentDidMount() etc..
- React Hooks [Functions]
useState()
useEffect()
useContext() etc..

FAQ: What are the issues with Javascript as language?

Ans:
- It is not strongly typed.
- It is not implicitly strictly typed.
- It is not an OOP language.
- It is an OBPS. [Object Based Programming System]
- Extensibility issues
- No Dynamic Polymorphism
- No Code Level Security
TypeScript

- Typescript is a strictly typed mode of Javascript.

- It is a strongly typed language.

- It is built with Typescript.

- It supports all low level features.

- It can directly interact with OS and hardware services.

- It can build large scale applications.

- It is an OOP language.

- Anders Heijlberg is the architect of Typescript. [ Known for C# language]

- It is a Microsoft Language.
- Typescript is trans compiled into Javascript.

Developer => Typescript => Translated => Javascript => Browser

Typescript Architecture

19 February 2026

1. Core Compiler

- It is responsible for translating the typescript code into OS native.

- It identifies the issues in code and reports as errors.

- Compiler manages various interactions through different components


[Link] loads the core library required for program.

[Link] checks the code blocks and execution flow.

[Link] responsible for handling input.

[Link] responsible for handling output.

[Link] verifies the data types.

[Link] responsible for converting one type to another.

etc.

2. Standalone TS compiler

- It is a trans compiler responsible for translating Typescript code into Javascript.

- "[Link]" handles trans compiling.

3. Language Service

- Service is a pre-defined business logic.

- It is a set of factories with functions & values required for typescript application.

- "[Link]" handles library.

- It is OS relative library.

4. Managed Language Service

- Managed code is the code understandable to every operating system service.

- It makes the library OS neutral.

5. Shims Library

- Shim is a library used to make platform independent services.

- It is responsible for converting the "unmanaged" code into "managed" code.

- "[Link]" manages all interactions on unmanaged code.

6. TS Server

- Typescript provides a native server to host application.

- It handles request and response.

- It can process the application in processing pipeline.

- "[Link]" handles the server.

Setup Typescript & Create Typescript Project:


1. Open your command prompt or terminal
> npm install -g typescript

2. Check the version of typescript


> tsc -v

3. Create a new folder for typescript project


D:\ts-project

4. Open in visual studio code

5. Run the following commands in project terminal


> npm init -y => generates [Link]
> tsc -init => generates [Link]

Note: "[Link]" is typescript configuration and language analysis tool.


Early version use 2 files:
a) [Link]
b) [Link]

6. Add a new file into project "[Link]" with following code


[Link]("Welcome to Typescript");

7. Compile from terminal


> tsc [Link] => generates [Link]

6. Run [Link] with node compiler


> node [Link]

Typescript Language:

20 February 2026

1. Variables

2. Data Types

3. Operators

4. Statements

5. Functions

6. OOPS

7. Modules & Namespaces


Variables & Data Types

- Variable configuration in typescript comprises of

a) keyword [var, let, const]

b) data type [any Javascript data type]

Syntax:

keyword variableName: dataType; // declaration

keyword variableName: dataType = value; // initialization

Ex:

let price:number = 1000;

let name:string = "A";

let stock:boolean = true;

- All Javascript primitive types are same

number, boolean, string, null, undefined, symbol, bigint

- Typescript supports type inference. The data type can be determined according
to

the value initialized.

- If value is not defined then the default is "any" type, which is the root for all
types.

let age; // age is any

age = 10; // valid

age = "A"; // valid

let age = 20; // age is number

age = "A"; // invalid

- Typescript supports "union" of types. It allows to configure multiple types.

let uname : null | string = prompt(91Enter Name');

let x : number | string | boolean;

- All number methods, string methods and other manipulations on primitive types
are
same as in Javascript.

let price:number = 4000;

[Link](), toLocaleString(), toPrecision()

isNaN(price) etc..

let name:string = "John";

[Link]

[Link]()

[Link]() etc..

Handling Non Primitive & Complex types:

1. Array

- Typescript array can handle various types like Javascript and can also restrict

array to similar type of values.

Syntax:
let names:string[] = new Array();
let names:string[] = [ ];
let values:any[] = [ ];
values[0] = 10;
values[1] = "A";
values[2] = true;

- You can't initialize various types of values using an array constructor even when
the data type is any.

- You can handle various types assignment not initialization.


let values:any[] = new Array(10, "A"); // invalid first value type is used for
others.
let values:any[] = [ 10, "A", true]; // valid
- Array constructor will allow assignment of various types but will not allow initialization when data type is
defined as any.
let values:any[] = new Array();
values[0] = 10;
values[1] = "A"; // valid
values[2] = true; // valid
- If array is allowed with a collection of various types of values initialization & assignment then it is known as
a Tuple.
let values:any[] = [ ]; // tuple

- Array can configure union of types. However it will not allow to initialize all types

defined in union. You can assign all types in union.


let values:string[] | number[] = [ 10, "A" ] ; // invalid
[ 10, 20 ] ; // valid
[ "A", "B"] ; // valid
values[0] = 10; // valid
values[1] = "A"; // valid

- All array methods are same as in Javascript.

2. Object

- Typescript object type is schema based.

- It configures structured data.

- Properties defined in structure are mandatory to configure. [default rule]

Syntax:

let obj : {property:datatype, property:datatype} = { }

let product : {Name:string, Price:number} = { }

- It supports optional properties defined with "?", which is a null reference

character.

Syntax:

let product : {Name:string, Price:number, Rating?:number= { }

// Rating is optional in product

- It supports read-only properties, you can initialize a value but can't assign.

Syntax:

let product : {Name:string, readonly Price:number} = {


Name:"TV",

Price: 3000
}

[Link] = 3400; // invalid Price is read-only property.

- All object manipulations are same as in Javascript.

Ex:

let product:{Name:string, readonly Price:number, Stock:boolean, Rating?:number} = {


Name : "TV",
Price: 3000,
Stock: true
}
[Link] = 5000;
if([Link]){
// then print with rating
} else {
// print without rating
}

FAQ: How to configure array of objects?

Ans: It requires a schema with array meta character.


let data: {property:datatype} [ ] = [ ];

EX:

let products:{id:number, title:string, price:number, rating:{rate:number}}[] = [


{id:1, title:'tv', price:4500, rating:{rate:2.3}},
{id:1, title:'tv', price:4500, rating:{rate:2.3}}
];

3. Map Type is same as in Javascript


let data:Map<T, K> = new Map();

- Typescript allows to configure a data type for key and value.

- Javascript Map can have any type of key or value.

Syntax:
let data: Map<key_datatype, value_datatype> = new Map()

let data: Map<number, string> = new Map();


[Link](1, "A");
[Link](2, "B");
let data: Map<string, any> = new Map();
[Link]("A", [ ]);
[Link]("B", { });

- Map manipulations are same as in Javascript.

21 February 2026

- Primitive Types

- Non Primitive

- Union of Types

- Type Inference

- Tuple

- Map Generic
Date Type:

- It is configured using Date data type and Date constructor.

- All date and time methods are same.

Syntax:
let departure:Date = new Date("yy-mm-dd hrs:min:sec");

Regular Expression Type:

- It is set of meta chars and quantifiers defined in "/ /".

- Typescript provides RegExp as type for regular expression.

Syntax:
let pattern:RegExp = /^\d{10}$/;

- It is verified by using string match() method.

Note: Statements & Operators are same as in Javascript.


Typescript Function

- A typescript function requires the return type to configure or to keep void.

- It requires data type for parameters.

Syntax:
function Name(params:dataType) : void | dataType
{
return value; // if not void
}

Ex:
function Add(a:number, b:number) : number
{
return a + b;
}

- You can configure optional parameters using "?", but it requires to verify by
using

undefined.

- All optional parameters must be last in formal list.

Syntax:
function Name(param1:type, param2?type)
{
if(param2) {
// when defined
}
}

Ex:

function Details(id:number, name:string, price?:number, rating?:number){


if(price){
// use price
} else {
// without price
}
}
Details(1, "TV");

- Rest parameter is defined as array. You can allow various types of arguments

or restrict to specific type.

Syntax:
function Name(...params:any[]) : void
{
}
Name(1, 91TV, true);

- Function currying and higher order functions require the type defined using

"Function" interface.

Syntax:
function Name(success:Function, failure:Function) : Function
{
}

Ex:

function Validation(password:string, success:Function, failure:Function){


if(password==='abc'){
success();
} else {
failure();
}
}
Validation('abc', function(){}, function(){})

Typescript OOP

1. Contracts

- A contract defines rules for designing component.

- It is easy to extend, reuse, maintain and test contracts.

- It must contain only rules not their implementation.

- Contract in OOP is designed using "interface".


Syntax:
interface Name
{
// rules
}
let obj : Name = { }

- Rule can be for a property or method.

Syntax:
interface Name
{
property: type;
method(): type;
}

Ex:

interface IProduct
{
Name:string;
Price:number;
Qty:number;
Total():number;
Print():void;
}
let product:IProduct = {
Name: 'TV',
Price: 34000,
Qty: 2,
Total: function(){
return [Link] * [Link];
},
Print: function(){
[Link](`Name=${[Link]}`);
}
}
[Link]();

- It can have optional rules defined using "?"

- Optional rules are required to configure Goal for a module.


[objective : time bound and mandatory ]
[goal : no time bound and optional ]

- It can have readonly rules.

- It allows to initialize but will not allow to assign.

- You can extend rules.

- A contract can be extended, it is the process of adding new rules without

disturbing the existing.

Syntax:
interface Contract1
{
}

interface Contract2 extends Contract1


{
}

interface Final extends Contract1, Contract2


{
}

Ex:

interface ICategory{

CategoryName: string;
}
interface IVendor{
VendorName:string;
}

interface IProduct extends ICategory, IVendor


{
Name:string;
readonly Price:number;
Qty:number;
Rating?:number;
Total():number;
Print():void;
}
let product:IProduct = {
Name: 'TV',
Price: 34000,
Qty: 2,
CategoryName: 'Electronics',
VendorName : 'Reliance Digital',
Total: function(){
return [Link] * [Link];
},
Print: function(){
[Link](`Name=${[Link]}`);
}
}
[Link] = 60000;
[Link]();

2. Components

- Class is considered as a component.

- Typescript class is similar to Javascript class with few changes

a) It can have static and non static members [ available in JS latest ]

b) It provides access modifiers [public, private, protected]

- It can implement a contract.


22 February 2026

- Contracts

interface

- Component

class

class implements contract

class can implement multiple contracts [multiple, multilevel]

class have static & non-static

class members same

a) property

b) accessor

c) constructor

d) method

Access Modifiers:

a) public
- It is default access modifier.
- It allows access from any location and through any object.
- You can access with super or derived class object.

b) private
- It is accessible only with in the defined class.

c) protected
- It is accessible within the defined class.
- It is accessible outside class but inside derived class and only by using
derived class reference.

Ex:

class Product
{
public Name:string = "TV";
private Price:number = 53000;
protected Stock:boolean = true;
}
class Derived extends Product
{
public Print(obj1:Derived){
[Link];
[Link];
}
}
let obj = new Derived();
[Link];

Note: Every member of class is defined with type.

Property, method and arguments are strongly typed.

3. Templates

- Template comprises of pre-defined design and logic, which you can customize

and implements according to requirements.

- Templates are used to hide the structure and provide only functionality.

- They are required in rollouts and various module implementations in application

development.

- The process of hiding the structure and providing only functionality is known as

Abstraction.

- Templates are designed as "Abstract Classes"

Syntax:

abstract class Name


{
abstract Property:type; ] //abstract
abstract Method():type; ]
Property:type; // non abstract
}

- Abstract members are implemented using derived class.

Ex:

interface ProductContract
{
Name:string;
Price:number;
Qty:number;
Total():number;
Print():void;
}

abstract class ProductTemplate implements ProductContract


{
public Name:string = "";
public Price:number = 0;
public Qty:number = 0;
public abstract Total():number;
public abstract Print():void;
}

class ProductComponent extends ProductTemplate


{
Name = "TV";
Price = 34000;
Qty = 2;
Total(){
return [Link] * [Link];
}
Print(){
[Link](`Name=${[Link]}\nPrice=${[Link]}\nQty=${[Link]}\nTotal=${[Link]()}`);
}
}

let obj = new ProductComponent();


[Link]();

4. Generics

- Generics are used to configure Type Safe content.

- A type safe member is open for any type and strongly typed for specific data
type.

- In OOP

a) Function can be generic

b) Parameters can be generic

c) Class can be generic

d) Property & Method can be generic

e) Constructor can be generic


[ not supported in Typescript that trans compiles into Javascript ]

Syntax:
function Name<Type>(params:Type): Type
{
}

Syntax:

class Name<T>
{
constructor(param:T) { }
property : T;
method<T>(): T { }
}

Ex:
interface MySQL

{
host:string;
user:string;
password:string;
database:string;
}

interface MongoDB
{
url:string;
}

class Database<T>
{
constructor(connectionString:T){
for(var property in connectionString){
[Link](`${property} : ${connectionString[property]}`);
}
}
}

let mysql = new Database<MySQL>({host:'localhost', user:'root', password:'1234', database:'productdb'});


let mongodb = new Database<MongoDB>({url:'mongodb://[Link]:27017'});

Ex:

interface IProduct
{
id:number;
title:string;
price:number;
}
interface IEmployee{
firstName:string;
designation:string;
}

class FetchAPI<T>
{
constructor(response:T){
[Link](response);
}
}

let product = new FetchAPI<IProduct>({id:1, title:'tv', price:34000});

let products = new FetchAPI<IProduct[]>([{id:2, title:'mobile', price:50000}]);

Enum, Namespace

24 February 2026

- Generic

- Templates

Enumeration

- It is a collection of constants.
- Constant can be number, string or expression.

- Numeric constants auto implement based on pervious value.

- A numeric constant increments the previous value and assigns to reference.

Syntax:

enum Name
{
Key = value,
Key = value
}

- It can have any expression that returns a number or string.

- You can access value with reference of Key.

Syntax:
[Link]

- It supports reverse mapping, which allows to access key with reference of value.

Syntax:
Name[value]

Ex:
enum StatusCodes

{
Found=200,
NotFound = 404,
ClientError,
Error = "Something went wrong",
Status = 505,
A = 10,
B = 20,
C = A + B
}
[Link](`${[Link]} : ${StatusCodes[404]}`);

Namespace

- It is a collection of sub-namespaces and members like contracts, components,

templates, functions and values.

- It is used to build a library for high level projects to reduce ambiguity.

Syntax:
namespace Parent
{
namespace Child
{
// contracts
// templates
// components
// functions
// values
}
}
[Link]

- Namespace is imported from any module system using "///<reference />"


directive.
///<reference path="../folder/[Link]" />
[Link] // directly accessing a member

- You can alias by using "import" statement


import AliasName = [Link];
AliasName => refers to member of namespace

Ex:

1. Library/contracts/[Link]

namespace Project
{
export namespace Contracts
{
export interface ProductContract
{
Name:string;
Price:number;
Qty:number;
Total():number;
Print():void;
}
}
}

2. Library/template/[Link]
///<reference path="../contracts/[Link]" />

import ProductContract = [Link];

namespace Project
{
export namespace Templates
{
export abstract class ProductTemplate implements ProductContract
{
public Name:string = "";
public Price:number = 0;
public Qty:number = 0;
public abstract Total():number;
public abstract Print():void;
}
}
}
3. Library/components/[Link]
///<reference path="../templates/[Link]" />

import ProductTemplate = [Link];

namespace Project
{
export namespace Components
{
export class ProductComponent extends ProductTemplate
{
Name = "TV";
Price = 45000;
Qty = 2;
Total(){
return [Link] * [Link];
}
Print(){
[Link](`Name=${[Link]}\nPrice=${[Link]}\nQty=${[Link]}\nTotal=${[Link](
}
}
}
}

4. App/[Link]

///<reference path="../library/components/[Link]" />

import ProductComponent = [Link];

let obj = new ProductComponent();


[Link]();

5. Create an out file


> tsc -outFile app/[Link] app/[Link]
> node [Link]

React Typescript App

1. Run the following command in your command prompt or terminal

> npm create vite@latest react-ts-app


Framework : React
Variant : Typescript

2. Open project folder in VS code and run the application

> npm run dev

3. New File System comprises of Typescript configuration files

a) [Link] => app configuration for react environment

b) [Link] => Typescript LINT


c) [Link] => Compiler configuration

4. Configuring files
.tsx => components, hooks, uncontrolled, main, store, slicer
.ts => contract, templates
function Login() : [Link]
{
return( <div> </div>);
}

State:

- Typescript useState() is generic type.

- It requires a data type to configure.

Syntax:

const [get, set] = useState<T>( );

- You can access the values directly from state if it contains initialization.

- If not initialized the you have to use optional chaining technique.

const [products] = useState<ProductContract[]>([ ]);

{ [Link]() }

const [products] = useState<ProductContract[]>( );

{ products?.map() }

Contracts:

- In module system importing contract requires "type" from latest version.


import { Contractname } from "module"; // old technique
import { type ContractName } from "module"; // new and valid in latest

Libraries:

- All 3rd party libraries are same


a) axios
b) formik
c) hookform
d) mui
e) react-cookie
f) redux etc..

Ex:

1. Src/contract/[Link]
export interface FakestoreContract

{
id:number;
title:string;
price:number;
description:string;
image:string;
rating:{rate:number, count:number};
category:string;
}

2. Components/[Link]
import { useEffect, useState } from "react"

import { type FakestoreContract } from "../../contracts/fakestore-contract";


import axios from "axios";

export function DataBinding(){

const [products, setProducts] = useState<FakestoreContract[]>();

useEffect(()=>{

[Link]('[Link]
.then(response=>{
setProducts([Link]);
})

},[])

return(
<div style={{padding:'20px'}}>
<h3>Products</h3>
{
products?.map(product=> <p key={[Link]}>{[Link]}</p>)
}
</div>
)
}

25 February 2026

- Props in controlled component is configured as Object type.

- It uses a schema or contract to define type.

Syntax:

export function Navbar(props:{key:dataType})


{
}
Event Type

- All events are derived from SyntheticEvent base.

- Event arguments are of SynthenticEvent type.

Syntax:

function handleChange(e: SyntheticEvent)


{
}

Route Object in Javascript & Typescript

- React applications that change their routes regularly and need frequent
extensions

are configured with Router Object.

- Javascript is not strongly typed hence it can configure object directly.

Javascript Router Object

1. Create a new routes folder and add into "src".

2. Add a new file "[Link]"

3. Configure routes

export const router = createBrowserRouter([


{
path: 91/91,
element: <E />,
children: [
{ path:'child', element=<C /> }
]
}
])

4. Go to "[Link]"

import { RouteProvider} from 91react-router-dom';

import { router } from 91routes/routes';

<RouteProvider router={router} />

Ex: routes/[Link]

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

import { FoodIndex } from "../food-delivery/food-index";


import { FoodMenu } from "../food-delivery/food-menu";
import { NotFound } from "../food-delivery/not-found";
import { FoodDetails } from "../food-delivery/food-details";
export const router = createBrowserRouter([
{
path: '/',
element: <FoodIndex />,
errorElement: <NotFound />
},
{
path:'/menu',
element: <FoodMenu />,
children: [
{
path:'details',
element: <FoodDetails />
}
]
},
{
path:'*',
element: <NotFound />
}
])

Typescript Router Object

1. Create routes folder in "src"

2. Add "[Link]"

3. Configure routes collection as RouteObject type.

import { createBrowserRouter, type RouteObject } from 91react-router-dom';

const routes : RouteObject[] = [


{
path: 91/91,
element: <Component/>,
children: [ ]
}
];

export const router = createBrowserRouter(routes);

4. Router Provider in [Link] is same

<RouteProvider router={ router } /> => router from routes/[Link]

Ex: [Link]

import { createBrowserRouter, type RouteObject} from "react-router-dom";

const routes:RouteObject[] = [
{
path:'',
element: <></>
}
]
export const router = createBrowserRouter(routes);
Typescript Video Library Project

Modules:

1. Admin

- Can login , Dashboard

- Upload Video [YouTube Embedded]

- Edit Video

- Delete Video

- Filter, Sort, Pagination

2. User

- Can register

- Can Login

- User Dashboard

- User can view, search, sort, like, dislike, comment

- Save video to watch later [Redux]

Technologies [MERN Stack App]

- React for UI

- Express JS middleware

- Node JS for server


- MongoDB for database

For Backend :

> npm install express cors mongodb --save

For Front End:


> npm install formik yup axios react-router-dom react-cookie bootstrap bootstrap-icons @reduxjs/toolkit
react-redux @mui/material @emotion/styled @emotion/react

You might also like