React JS Notes
React JS Notes
UNIT - IV
Introduction to React
What is ReactJS?
● React JS is a popular JavaScript library used to build interactive user interfaces
(UI)—especially for single-page applications (SPAs).
● React is used to build the user interface (UI) — what users see and interact with
in the browser.
1. What is a Library?
● A library is a collection of pre-written code that developers use to perform
common tasks without writing everything from scratch.
Key Points
Library Framework
i. HTML with JS
<!DOCTYPE html>
<html>
<body>
<div>
3
<h1 id="title">Hello</h1>
<button onclick="changeText()">Click Me</button>
</div>
<script>
function changeText() {
[Link]("title").innerHTML = "Hello Teja!";
}
</script>
</body>
</html>
Question: How does React update a specific <h1> element when a button is clicked,
especially if there are multiple <h1> tags in the component?
In React, the button does NOT “find” the <h1> tag at all
There is:
4
● No getElementById
● No DOM searching
Flow:
What happens?
● First <h1> → uses {text} → will update
● Second <h1> → static → will NOT change
Important Concept
Instead of directly updating the browser DOM (which is slow), React updates this virtual
DOM copy first, then efficiently applies only the necessary changes to the real DOM.
The Virtual DOM (VDOM) is a lightweight JavaScript copy of the real DOM.
6
<h1>{text}</h1>
● Before: <h1>Hello</h1>
● After: <h1>Hello Teja!</h1>
React updates only the text inside <h1>, not the whole element
7
React follows:
“Compare → Find difference → Update only that part”
React is popular because of a few powerful core features that make UI development
fast and scalable
1. Component-Based Architecture
2. Virtual DOM
● Functions that let you use state and lifecycle in functional components
11
6. State Management
7. Reusability
8. Strong Ecosystem
9. Declarative UI
Check:
node -v
npm -v
● Framework → React
● Variant → JavaScript
Project Structure
my-react-app/
├── [Link]
├── [Link]
├── src/
│ ├── [Link]
│ ├── [Link]
│ └── assets/
Important Files
[Link]
[Link]
function App() {
return <h1>Hello React</h1>;
}
export default App;
17
[Link]([Link]('react-widget')).render(<
Widget />);
</script>
1. JSX
2. Components
3. Props
4. State
18
Example:
PipeLine:
JSX Code
↓
Transpiler
↓
JavaScript
↓
Virtual DOM
↓
Diffing Algorithm
↓
Real DOM (Browser UI)
19
This looks like HTML but is actually not valid JavaScript. browsers do NOT
understand JSX directly.
Tools like:
● Babel
● Vite
Props: properties
Transformed into:
Transformed into
"react/jsx-runtime"
Transformed into:
<div>
<h1>Hello</h1>
<p>Hi</p>
</div>
21
Transformed into:
_jsxs("div", {
children: [
_jsx("h1", { children: "Hello" }),
_jsx("p", { children: "Hi" })
]
});
JSX Code
↓
Transpiler (Babel / Vite)
↓
JavaScript (createElement / jsx-runtime)
↓
Virtual DOM (JS Objects)
↓
Diffing Algorithm
↓
Real DOM (Browser UI)
Without JSX:
● Cleaner
● Shorter
● More readable
Rules of JSX
4. Self-closing Tags
<img src="[Link]" />
<button onClick={handleClick}></button>
—-------------------------------------------------------------
Syntax:
function ComponentName() {
return (
<JSX />
);
}
Step-by-step:
Types of Components
There are two primary types of React components:
1. Class Components
When creating a React component, the component's name must start with an upper
case letter.
render() {
Now your React application has a component called Car, which returns a <h2> element.
To use this component in your application, use similar syntax as normal HTML: <Car />
Purpose
● Initialize state
● Setup initial values
Required to access:
● [Link]
● [Link]
Example of Prop
Props are like function arguments, and you send them into the component as attributes.
26
Use an attribute to pass a color to the Car component, and use it in the render
function:
Example of State
Create a constructor function in the Car component, and add a color property:
import React from 'react';
import { createRoot } from 'react-dom/client'
class Car extends [Link] {
constructor() {
super();
[Link] = {color: "red"};
}
render() {
return <h2>I am a {[Link]} Car!</h2>;
}
}
createRoot([Link]('root')).render(
<Car />
);
—-----------------------------------
changeColor = () => {
[Link]({ color: "blue", model:"BMW" });
};
render() {
return (
<div>
<h2 style={{ color: [Link] }}>
I am a {[Link]} Car!
</h2>
28
Who owns it? Owned by parent component Owned and managed by the
component itself
29
Purpose Pass data from parent to child Manage internal data that can
change over time
Components in Components
);
}
}
createRoot([Link]('root')).render(
<Garage />
);
Before React 16.8, Class components were the only way to track state and lifecycle on
a React component. Function components were considered "state-less".
2. Functional Components
Functional components are JavaScript functions that return React elements
and are the preferred way to build modern React applications.
function App() {
return <h1>Hello World</h1>;
}
{
type: 'h1',
props: { children: 'Hello World' }
}
These components also work together cohesively through React’s unidirectional data
flow, where data is passed from parent to child using props. This ensures better control
over data and makes debugging and maintenance easier, as changes in one component
do not unnecessarily affect others. Overall, this modular design promotes scalability,
maintainability, and clean separation of concerns, enabling developers to build efficient
and well-organized applications.
32
ReactJS and React Native are both popular JavaScript libraries used for
building user interfaces. While they share similar concepts, they are used
for different platforms and purposes.
A React component has three different phases in its lifecycle, including mounting,
updating, and unmounting. Each phase has its own methods which are responsible for
a particular stage in a component’s lifecycle.
34
React has four built-in methods that gets called, in this order, when mounting a
component:
1. constructor()
2. getDerivedStateFromProps()
3. render()
4. componentDidMount()
The render() method is required and will always be called, the others are optional and
will be called if you define them.
35
1. Constructor()
The constructor() method is called before anything else, when the component is
initiated, and it is the natural place to set up the initial state and other initial values.
The constructor() method is called with the props, as arguments, and you should
always start by calling the super(props) before anything else, this will initiate the
parent's constructor method and allow the component to inherit methods from its parent
([Link]).
Example:
The constructor() method is called, by React, every time you make a component:
Run Example
2. getDerivedStateFromProps()
36
This is the natural place to set the state object based on the initial props.
It takes state as an argument, and returns an object with changes to the state.
The example below starts with the favorite color being "red", but the
getDerivedStateFromProps() method updates the favorite color based on the
favcol attribute:
Run Example
3. render()
37
The render() method is required, and is the method that actually outputs the HTML to
the DOM.
Run Example
4. componentDidMount()
This is where you run statements that requires that the component is already placed in
the DOM.
Example: At first my favorite color is red, but give me a 5 second, and it is yellow
instead:
componentDidMount() {
setTimeout(() => {
[Link]({favoritecolor: "yellow"})
}, 5000)
}
render() {
return (
<h1>My Favorite Color is {[Link]}</h1>
);
}
}
createRoot([Link]('root')).render(
<Header />
);
Run Example
—--------------------------------------------------------------------------------------------------------------------------------
React has five built-in methods that gets called, in this order, when a component is
updated:
1. getDerivedStateFromProps()
2. shouldComponentUpdate()
3. render()
4. getSnapshotBeforeUpdate()
5. componentDidUpdate()
39
The render() method is required and will always be called, the others are optional and
will be called if you define them.
1. getDerivedStateFromProps
This is still the natural place to set the state object based on the initial props.
The example below has a button that changes the favorite color to blue, but since the
getDerivedStateFromProps() method is called, which updates the state with the
color from the favcol attribute, the favorite color is still rendered as yellow:
Example:
If the component gets updated, the getDerivedStateFromProps() method is called:
</div>
);
}
}
createRoot([Link]('root')).render(
<Header favcol="yellow" />
);
/*
This example has a button that changes the favorite color to blue,
but since the getDerivedStateFromProps() method is called,
the favorite color is still rendered as yellow
(because the method updates the state
with the color from the favcol attribute).
*/
Run Example
[Link]
Example:
Stop the component from rendering at any update:
super(props);
[Link] = {favoritecolor: "red"};
}
shouldComponentUpdate() {
return false;
/* return true; */
}
changeColor = () => {
[Link]({favoritecolor: "blue"});
}
render() {
return (
<div>
<h1>My Favorite Color is {[Link]}</h1>
<button type="button" onClick={[Link]}>Change
color</button>
</div>
);
}
}
createRoot([Link]('root')).render(
<Header />
);
/*
This example has a button that changes the favorite color to blue,
but since the shouldComponentUpdate() method is called,
the favorite color is still rendered as red
(because the method returns false).
*/
Run Example
3. render()
42
The render() method is of course called when a component gets updated, it has to
re-render the HTML to the DOM, with the new changes.
The example below has a button that changes the favorite color to blue:
Example:
Click the button to make a change in the component's state:
Run Example
43
4. getSnapshotBeforeUpdate
In the getSnapshotBeforeUpdate() method you have access to the props and state
before the update, meaning that even after the update, you can check what the values
were before the update.
The example below might seem complicated, but all it does is this:
When the component is mounting it is rendered with the favorite color "red".
When the component has been mounted, a timer changes the state, and after one
second, the favorite color becomes "yellow".
This action triggers the update phase, and since this component has a
getSnapshotBeforeUpdate() method, this method is executed, and writes a message
to the empty DIV1 element.
Example:
Use the getSnapshotBeforeUpdate() method to find out what the state object
looked like before the update:
setTimeout(() => {
[Link]({favoritecolor: "yellow"})
}, 1000)
}
getSnapshotBeforeUpdate(prevProps, prevState) {
[Link]("div1").innerHTML =
"Before the update, the favorite was " + [Link];
}
componentDidUpdate() {
[Link]("div2").innerHTML =
"The updated favorite is " + [Link];
}
render() {
return (
<div>
<h1>My Favorite Color is {[Link]}</h1>
<div id="div1"></div>
<div id="div2"></div>
</div>
);
}
}
createRoot([Link]('root')).render(
<Header />
);
Run Example
5. componentDidUpdate
The example below might seem complicated, but all it does is this:
When the component is mounting it is rendered with the favorite color "red".
45
When the component has been mounted, a timer changes the state, and the color
becomes "yellow".
This action triggers the update phase, and since this component has a
componentDidUpdate method, this method is executed and writes a message in the
empty DIV element:
Example:
The componentDidUpdate method is called after the update has been rendered in the
DOM:
);
Run Example
—----------------------------------------------------------------------------------------------------------------------------
3. Unmounting
The next phase in the lifecycle is when a component is removed from the DOM, or
unmounting as React likes to call it.
React has only one built-in method that gets called when a component is unmounted:
● componentWillUnmount()
componentWillUnmount
};
return (
<div>
{myheader}
<button type="button" onClick={[Link]}>Delete
Header</button>
</div>
);
}
}
class Child extends [Link] {
componentWillUnmount() {
alert("The component named Header is about to be unmounted.");
}
render() {
return (
<h1>Hello World!</h1>
);
}
}
const root = [Link]([Link]('root'));
[Link](<Container />);
Run Example
48
React uses the camelCase convention for event names, which differs from the standard
HTML event names (e.g., onClick instead of onclick).
<html>
<body>
<button id="btn">Click Me</button>
<p id="count">Count: 0</p>
<script>
let count = 0;
49
const button = [Link]("btn");
const display = [Link]("count");
// function (event handler)
function handleClick() {
count++;
[Link] = "Count: " + count;
}
// Attach function to event
[Link]("click", handleClick);
</script>
</body>
</html>
In React, event handlers are added directly to elements via JSX attributes.
import { useState } from "react";
function App() {
const [count, setCount] = useState(0);
const handleClick = () => {
setCount(count + 1);
//setCount(prev => prev + 1);
//This ensures correct updates when multiple clicks happen fast.
};
return (
<div>
50
<button onClick={handleClick}>
Click Me
</button>
<p>Count: {count}</p>
</div>
);
}
export default App;
It means:
<App step={2}/>
Step 1: [Link]
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import App from './[Link]'
import Counter from './example/[Link]'
// Rendering a Component
createRoot([Link]('root')).render(
<StrictMode>
<App step={2} />
</StrictMode>,
)
Instead of always displaying the same UI, React decides what to render
depending on state/props.
So:
● UI = function of state
● Change state → React re-renders → UI changes automatically
Different Methods:
function App() {
const [isLoggedIn, setIsLoggedIn] = useState(false);
if (isLoggedIn) {
return (
<div>
<h1>Welcome User</h1>
<button onClick={() => setIsLoggedIn(false)}>Logout</button>
</div>
);
}
return (
55
<div>
<h1>Please Login</h1>
<button onClick={() => setIsLoggedIn(true)}>Login</button>
</div>
);
}
● Entire UI changes based on condition
● Only ONE return executes
function App() {
const [isLoggedIn, setIsLoggedIn] = useState(false);
return (
<div>
<h1>{isLoggedIn ? "Welcome User" : "Please Login"}</h1>
<button onClick={() => setIsLoggedIn(!isLoggedIn)}>
{isLoggedIn ? "Logout" : "Login"}
</button>
</div>
);
56
The && operator returns the second operand if the first is true, and nothing if
the first is false. This can be useful when you only want to render something
when a condition is true.
function App() {
const [notifications, setNotifications] = useState(3);
return (
<div>
<h1>Dashboard</h1>
{notifications > 0 && (
<p>You have {notifications} new notifications</p>
)}
<button onClick={() => setNotifications(0)}>
Clear Notifications
</button>
</div>
57
);
}
● No “else”
● Only renders when condition is true
Switch case statements are useful when you need to handle multiple
conditions, which would otherwise require multiple if conditions. This
approach can be more readable if there are many conditions to check.
function App() {
const [status, setStatus] = useState("loading");
const renderContent = () => {
switch (status) {
case "loading":
return <p>Loading...</p>;
case "success":
return <p>Data Loaded Successfully</p>;
case "error":
return <p>Error occurred</p>;
default:
58
return null;
}
};
return (
<div>
<h1>Status</h1>
{renderContent()}
<button onClick={() => setStatus("success")}>Success</button>
<button onClick={() => setStatus("error")}>Error</button>
</div>
);
}
● Best for multiple cases
● Cleaner than many if-else
function App() {
const items = ["apple", "banana", "grape", "kiwi"];
return (
<div>
<h1>Fruits with letter 'a'</h1>
{[Link]((item, index) =>
[Link]("a") ? <p key={index}>{item}</p> : null
)}
</div>
);
}
React encourages using JavaScript arrays and generating UI using .map() method.
.map() is a JavaScript array method used to: Transform each element of an array into
a new value
There are two common ways to use .map()—with an implicit return and with an
explicit return.
Example:
function CarsList() {
const cars = ['Ford', 'BMW', 'Audi'];
return (
<ul>
{
[Link]((car) => (
<li>{car}</li>
))
}
</ul>
);
}
Example
function CarsList() {
const cars = ['Ford', 'BMW', 'Audi'];
return (
<ul>
{[Link]((car) => {
return <li>{car}</li>;
})}
</ul>
);
61
Why?
Because React needs a way to identify each item uniquely when updating the UI.
Example:
function CarsList() {
const cars = ['Ford', 'BMW', 'Audi'];
return (
<ul>
{[Link]((car, index) => {
return <li key={index}>{car}</li>
})}
</ul>
);
}
62
Keys allow React to keep track of elements. This way, if an item is updated or removed,
only that item will be re-rendered instead of the entire list.
If no keys:
With keys:
{[Link]} - ₹{[Link]}
</li>
))}
</ul>
);
}
4.10 Forms
React forms are all about handling user input (text fields, checkboxes, selects, etc.)
and managing that data inside your component state. If you understand forms well, you
can build login pages, search bars, registration systems, and more.
A form in React works similarly to HTML forms, but with extra control using state.
In plain HTML:
In React:
● State is a variable that stores data and can change over time, and when it
changes, React automatically updates the UI.
64
Just like in HTML, React uses forms to allow users to interact with the web page.
function MyForm() {
return (
<form>
<p>Enter your name:</p>
<input type="text" />
</form>
);
}
● This works like normal HTML
● But React does not control it yet
Handling Forms
Controlled Components:
function MyForm() {
const [name, setName] = useState("");
return (
<form>
<p>Enter your name:</p>
<input
type="text"
onChange={(e) => setName([Link])}
/>
<br/> you typed: <h2>{name}</h2>
</form>
);
}
65
How it works:
User types "Teja" -> onChange fires -> setName("Teja") -> React updates UI ->I/P shows "Teja"
Flow:
function MyForm() {
const [name, setName] = useState("");
const [submittedName, setSubmittedName] = useState("");
const handleSubmit = (e) => {
//[Link]();
setSubmittedName(name);
};
return (
<>
<form onSubmit={handleSubmit}>
<input onChange={(e) => setName([Link])} />
<input type="submit" />
</form>
You submitted: <h2> {submittedName}</h2>
</>
);
}
66
Multiple Inputs
function CricketForm() {
const [formData, setFormData] = useState({
player: "",
runs: "",
team: ""
});
const [submittedData, setSubmittedData] = useState(null);
// Handle all inputs
const handleChange = (e) => {
const { name, value } = [Link];
setFormData({
...formData, //Copy everything → Update only changed field → Keep rest
same
[name]: value
});
};
// Handle submit
const handleSubmit = (e) => {
[Link]();
setSubmittedData(formData);
};
return (
<>
<h2>Cricket Player Form</h2>
<form onSubmit={handleSubmit}>
<input
type="text"
name="player"
placeholder="Player Name"
value={[Link]}
onChange={handleChange}
/> <span style={{ padding: "1px" }}></span>
67
<input
type="number"
name="runs"
placeholder="Runs"
value={[Link]}
onChange={handleChange}
/><span style={{ padding: "2px" }}></span>
<input
type="text"
name="team"
placeholder="Team"
value={[Link]}
onChange={handleChange}
/><span style={{ padding: "2px" }}></span>
<button type="submit">Submit</button>
</form>
{submittedData && (
<div>
<h3>Submitted Data:</h3>
<p>Player: {[Link]}</p>
<p>Runs: {[Link]}</p>
<p>Team: {[Link]}</p>
</div>
)}
</>
);
}
State Lifting?
State Lifting means moving state from a child component to a common parent so
multiple components can share it.
If both need the same data → you keep it in a central scoreboard system (parent)
68
CricketForm()
App (Parent)
[Link] (Parent)
import CricketForm from './demo/CricketForm'
import ScoreBoard from './demo/ScoreBoard'
function App() {
const [submittedData, setSubmittedData] = useState(null);
return (
<>
<h2>Cricket Player Form</h2>
<CricketForm setSubmittedData={setSubmittedData} />
<ScoreBoard submittedData={submittedData} />
</>
);
}
export default App
};
return (
<form onSubmit={handleSubmit}>
<input
type="text"
name="player"
placeholder="Player Name"
value={[Link]}
onChange={handleChange}
/> <span style={{ padding: "1px" }}></span>
<input
type="number"
name="runs"
placeholder="Runs"
value={[Link]}
onChange={handleChange}
/><span style={{ padding: "2px" }}></span>
<input
type="text"
name="team"
placeholder="Team"
value={[Link]}
onChange={handleChange}
/><span style={{ padding: "2px" }}></span>
<button type="submit">Submit</button>
</form>
);
}
export default CricketForm;
Benefits
● Share data between components
● Centralized control
● Cleaner architecture
● Scalable apps
Without it
● Components isolated
● Data duplication
● Hard to manage
72