React JS
React JS
Page | 1
React JS
Advantages of MPAs:
SEO-Friendly: Each page has its own URL, making it easier for
search engines to index content.
Scalability: MPAs can handle large amounts of content across
multiple pages without performance degradation.
Simplicity: Ideal for simpler websites or those that do not
require dynamic interactions.
Disadvantages of MPAs:
Slower User Experience: Full-page reloads can lead to slower
navigation and a less seamless experience.
Increased Server Load: Each interaction requires
communication with the server, which can increase load times
Page | 2
React JS
Advantages of SPAs:
Faster Interactions: After the initial load, SPAs provide quick
responses to user actions since only data is transmitted between the
client and server.
Improved User Experience: The seamless transitions between
different views create a more app-like experience.
Offline Capabilities: Many SPAs can cache data for offline use,
allowing users to interact with the application even without an internet
connection.
Disadvantages of SPAs:
Initial Load Time: The first load may take longer as all necessary
resources must be fetched upfront.
SEO Challenges: SPAs can be less SEO-friendly since content is
often loaded dynamically after the initial page load.
Page | 3
React JS
When your page is loaded in your browser than it start filling (displaying)
this process is known as Runtime.
Figure 1
Figure 2
Figure 3
Figure 4
Figure 5
Page | 5
React JS
Figure 6
npm run dev gives you your project run path where u
can run your project.
Figure 7
Page | 6
React JS
Limitation of React
Component-Based Architecture
React's architecture is centered around components, which are
independent and reusable pieces of code. Each component
encapsulates its own logic and rendering, enabling modular
development. Components can be categorized into two main
types:
1. Functional Components:- These are simple JavaScript
Page | 7
React JS
Figure 8
Naming Conventions
Page | 8
React JS
Figure 9
Page | 9
React JS
Figure 10
To define a class component in React, you need to
create a class that extends `React.Component`. This allows
your class to inherit the functionality provided by the React
library.
To use your class component in another file, you need
to import it as :- import React from 'react';
Key Features of Class Components
a. State Management:- Class components can manage
their own state, which is useful for handling dynamic
data.
b. Lifecycle Methods:- They provide lifecycle methods
(like `componentDidMount` , `componentDidUpdate` ,
etc.) that allow you to hook into different stages of a
component's lifecycle.
c. Render Method:- The `render()` method is required
and is where you define the UI structure using JSX.
This method is responsible for returning the JSX that
represents the UI of the component.
d. Refs and DOM Interaction:- Class components can
directly interact with the DOM using refs, which provide
a way to access DOM elements or React components
Page | 10
React JS
imperatively.
e. Error Boundaries:- Class components can act as
error boundaries. They can catch JavaScript errors in
their child component tree and display a fallback UI
instead of crashing the entire application.
f. Inheritance:- Class components utilize JavaScript
class inheritance, extending from React.Component.
This allows them to inherit methods and properties from
React, enabling more complex behavior.
Do :- Don’t :-
<div> <div>
<div></div> <div></div>
<div></div> <div></div>
</div> </div>
<div></div> ->error
Important Considerations
Props Handling: Props are read-only in both function and
Page | 11
React JS
Figure 11
Page | 12
React JS
Page | 13
React JS
Figure 12
Page | 14
React JS
Figure 13
Then whenever you click on this “count is 0” button it will increase its
number like :-
Page | 15
React JS
Figure 14
JavaScript in JSX
Page | 16
React JS
Hard-Coded Values
A hard-coded value is fixed and cannot be changed
dynamically during runtime. In contrast, when fetching data
from a database or backend, you typically retrieve dynamic
values that can change based on user input or other factors.
Page | 17
React JS
return (
<ul>
{itemList}
</ul>
);
Page | 18
React JS
Important Considerations:
1) Keys: When using `map()` to render lists, each item should
have a unique "key" prop. The key helps React identify which
items have changed, are added, or are removed, and is crucial
for efficient updates to the DOM.
2) New Array: The map() method always returns a new
array. The original array is not modified.
3) Side Effects: While the callback function provided
to map() can have side effects, it's generally recommended to
use pure functions that focus on transforming the array
elements.
4) Alternatives: If you don't need to return a new array and are
only interested in side effects, forEach() or a for...of loop might
be more appropriate.
Example No.2:- Create an web page which display Square and Circle
Components alsouse appropriate css. Square must be function component and
Circle must be class component.
Create react js file same as displayed in instruction.
Then you get this list of files. Given in Figure 12.
Here you don’t have any need of .css files and assets folder
because it is created by default.
Than have to remove 1 line from main.jsx file which import index
file.
Clear your App.jsx file and start coding
import Square from "./Square";
import Circle from "./Circle";
function App(){
//let jsx = <h1>Hello Everyone</h1>
return (
<div style={{backgroundColor:"black",
Page | 19
React JS
height:"100vh"}}>
<div style={{display:"flex"}}>
<Square></Square>
<Square/>
<Square></Square>
<Square/>
</div>
<div style={{display:"flex"}}>
<Circle></Circle>
<Circle/>
<Circle></Circle>
<Circle/>
</div>
</div>
);
}
export default App;
Figure 15
Page | 20
React JS
Figure 16
In Visual Studio Code, snippets and keyboard shortcuts can help you write code more
efficiently
Snippets: Code snippets are templates that make it easier to enter repeating code
patterns, such as loops or conditional statements
CONCEPT OF INHERITANCE :-
In React, while inheritance can be used, it is generally
recommended to use composition for code reusability. Here's why
and how to properly manage data flow between components:
Understanding the Component Hierarchy
Page | 21
React JS
function App() {
const items = ['Home', 'About', 'Contact'];
Page | 22
React JS
return (
<div>
<Menu items={items} />
</div>
);
}
Page | 23
React JS
MANAGING STATE
If the child component needs to modify the data, you can pass a
function as a prop from the parent to the child. The child
component can then call this function to update the parent's state.
By using props and function passing, you maintain a clear flow of
data and control in your React application, making it easier to
understand and maintain.
Figure 17
So, `../` simply means "go back one directory."
CUSTOM HOOKS
Page | 24
React JS
Purpose
Key Characteristics
Page | 25
React JS
Example:
import { useState, useEffect } from 'react';
function useFetchData(url) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const fetchData = async () => {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! Status: $
{response.status}`);
}
const result = await response.json();
setData(result);
} catch (err) {
setError(err);
} finally {
setLoading(false);
}
};
fetchData();
}, [url]);
retained.
The code uses a hook. Specifically, it utilizes the useState hook. This
hook is crucial for managing state within the FoodItem component,
allowing it to preserve values across re-renders.
The useState hook is used to initialize and manage the num state
variable, which tracks the quantity of the food item.
Hooks are functions that let you "hook into" React state and lifecycle
features from functional components
Normal variables/constants:
Declared using const or let directly inside a functional
component.
Do not cause re-renders when their values change.
Are re-initialized on every render, so they don't maintain their
values across renders.
Changes to these variables will not trigger any UI update.
State variables (managed by useState):
Cause a re-render when their values change.
Preserve their values across re-renders.
Changes to these variables will trigger a UI update.
You also have to import useState. useState can change
your UI.
Example :
Page | 27
React JS
Figure 18
When using `useState`, you provide an initial value or default
value for the state variable.
Data Persistence
Page | 29
React JS
4. Reusable:
The biggest reason it's a custom hook is that you can
now reuse this useFetchData` function in multiple components.
You don't have to repeat the `useState`, `useEffect`, `fetch`, error
handling, etc., in every component that needs to fetch data.
`package.json`
Example :
Page | 30
React JS
Figure 19
Page | 31
React JS
`consol.log` :-
`console.log`
Is `const` a State?
return (
<div>
<h1>Count: {count}</h1>
<button onClick={increment}>Increment</button>
</div>
);
};
Page | 33
React JS
Characteristics:
Example:
import React, { useState } from 'react';
return (
<div>
<button onClick={() => addItem('Pizza')}>Add
Pizza</button>
<p>Ordered Items: {orderedItems.join(', ')}</p>
</div>
);
};
Page | 34
React JS
2. `setComponent` :-
Characteristics:
Example:
import React, { useState } from 'react';
Page | 35
React JS
};
3. `currentState` :-
Characteristics:
Not User-Defined: While you can use any name for this
parameter (e.g., `prevState`, `oldState`), it typically
represents the current state value when passed as an
argument to a setter function.
Example:
const [count, setCount] = useState(0);
Summary
Page | 37
React JS
`Filter()` FUNCTION :-
What it is: filter() is a built-in JavaScript array method.
Purpose: It creates a new array containing only the elements
from the original array that satisfy a condition (provided as a
function).
How it works: You pass a function to filter(). This function is
called for each element in the array. If the function
returns true for a particular element, that element is included in
the new array. If the function returns false, the element is
excluded. Importantly, filter() does not modify the original array.
Example:
const numbers = [1, 2, 3, 4, 5, 6];
Page | 38
React JS
How to Do It?
2. API Hosting
3. API Documentation
Page | 39
React JS
Tokens). This ensures that only authorized users can access your
API.
Common Practices
Page | 40
React JS
function App(){
const[component, setComponent] = useState("menu")
const[orderedItem, setOrderedItem]=useState([]);
Page | 41
React JS
Ingredients : {data.result.ingredients.map(ele=>{
return <p>{ele.name} <b>{ele.amount}</b></p>
})}
</div>
{ /* Bill Page */ }
{component === "menu" ? (<Menu
setComponent={setComponent} setOrderedItem={setOrderedItem}
/>) : (<Bill orderedItems={orderedItem} // Pass orderedItem
state
setComponent={setComponent}
setOrderedItem={setOrderedItem}
/> )}
</div>
)
}
return (
<div>
<div className="foodMenu_container">
{foodMenu.map((obj)=>{
return <FoodItem item={obj}
setOrderedItem={setOrderedItem}/>
})
}
Page | 42
React JS
function clickHandler(sym) {
if (sym === "+") {
setNum({ value: num.value + 1 });
setOrderedItem((currentState) => {
console.log("Adding Item:", item);
let result = currentState.filter((ele) => {
if (ele.name === item.name) {
return true;
}
});
if (result.length === 0) {
item.count = num.value + 1;
return [...currentState, item];
} else {
return currentState.map((ele) => {
if (ele.name === item.name) {
ele.count = num.value + 1;
}
return ele;
});
}
});
} else if (sym === "-") {
if (num.value > 0) {
setNum({ value: num.value - 1 });
setOrderedItem((currentState) => {
console.log("Removing Item:", item);
let result = currentState.filter((ele) =>
{
Page | 43
React JS
if (result.length > 0) {
return currentState.map((ele) => {
if (ele.name === item.name) {
if (ele.count > 1) {
ele.count -= 1;
} else {
return null;
}
}
return ele;
}).filter(Boolean);
}
return currentState;
});
}
}
}
return (
<div className='foodItem_container'>
<img src={item.imageUrl} alt="dish name"
width="200px" height="200px" />
<h3>{item.name}</h3>
<h4>{item.price}</h4>
<p>{item.description}</p>
<div>
<button onClick={() => { clickHandler("-") }}>
- </button>
<button> {num.value} </button>
<button onClick={() => { clickHandler("+") }}>
+ </button>
</div>
</div>
);
}
Page | 44
React JS
Create data.js file for your items data. It does not contain any
code but have your food items data in an array form.
let foodMenu= [{name:"Coffee", imageUrl:" https://_URL ",
description:"Lorem ipsum dolor ...", price:"200"},
Page | 45
React JS
return (
<div className="bill-container">
<h2>Bill Summary</h2>
{orderedItems.map((item, index) => (
<div key={index} className="bill-item">
<p>{item.count} x {item.name} = ₹
{item.price * item.count}</p>
</div>
))}
<h3 className="total">Total: ₹{total}</h3>
<button className="back-button" onClick={() =>
setComponent("menu")}>Back to Menu</button>
</div>
);
}
.maincontainer{
text-align: center;
color: blue;
font-size: 35px;
}
.recpies{
width: 20%;
margin: 20px auto;
font-size: 15px;
color: black;
border: 2px solid rgb(229, 13, 13);
border-radius: 5px;
box-shadow: 0px 0px 10px rgb(235, 10, 115);
}
Menu.css
.foodMenu_container{
Page | 46
React JS
width: 100vw;
display: flex;
font-size: 20px;
color: gray;
gap: 20px;
flex-wrap: wrap;
justify-content: space-around;
}
.foodItem_container{
width: 20%;
border: 1px solid gray;
border-radius: 10px;
box-shadow: 0px 0px 10px gray;
}
bill.css
.bill-container {
width: 35%;
margin: 10px auto;
border: 1px solid #ccc;
}
.bill-item {
color: black;
border: 1px solid #eee;
}
.total {
color: rgb(0, 128, 0);
font-size: 1em;
}
.back-button {
padding: 10px 15px;
background: #007bff;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
await KEYWORD :-
await is used in JavaScript to pause the execution of
an async function until a promise is resolved or rejected. In
Page | 47
React JS
Key Concepts
function MyComponent() {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const fetchData = async () => {
try {
const response = await
fetch('https://api.example.com/data');
if (!response.ok) {
throw new Error(`HTTP error! Status: $
{response.status}`);
}
const result = await response.json();
setData(result);
} catch (err) {
Page | 48
React JS
setError(err);
} finally {
setLoading(false);
}
};
fetchData();
}, []);
return (
<ul>
{data.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
);
}
export default MyComponent;
In this example:
fetchData is an async function.
`await fetch('https://api.example.com/data')` pauses
execution until the fetch operation completes.
`await response.json()` pauses execution until the
JSON data is parsed.
The `try...catch` block handles potential errors during
the fetch operation.
2. Performing Other Asynchronous Tasks: You can
use await with any function that returns a promise.
import React, { useState, useEffect } from 'react';
function MyComponent() {
const [message, setMessage] = useState('');
Page | 49
React JS
useEffect(() => {
const showMessage = async () => {
await delay(2000); // Wait for 2 seconds
setMessage('Hello after 2 seconds!');
};
showMessage();
}, []);
return <p>{message}</p>;
}
1. Improved Readability:
await makes asynchronous code look and behave a bit
more like synchronous code, which can make it easier
to read and understand.
2. Simplified Error Handling:
You can use try...catch blocks to handle errors in
asynchronous code, which is often cleaner than
using .then() and .catch() with promises.
3. Sequential Execution:
await ensures that asynchronous operations are executed in a
specific order. This can be important when one operation
depends on the result of another.
Important Notes :-
Page | 50
React JS
1. Top-Level await:
Outside of an async function, you cannot use await directly in a
top-level context (e.g., in a module scope). If you're using ES
modules and a modern environment, top-level await may be
supported.
2. React Component Rendering:
You cannot use await directly within the render method of a
React component because the render method must be
synchronous. However, you can use it within useEffect or other
asynchronous functions triggered by component lifecycle
events or user interactions.
Summary
Page | 51
React JS
Page | 52
React JS
changes
return (
<div>
{userData ? (
<p>Welcome, {userData.name}!</p>
) : (
<p>Loading...</p>
)}
</div>
);
}
3. No list at all (don't put [ ] or anything):
Meaning: Run the code every single time the
component shows up on the screen.
Think: "Do this every time, no matter what!"
Warning: Usually, you don't want to do this! It can
make your website slow! Only do this if you really need
the code to run every time.
Important rules:
List everything your code uses: If your code
inside useEffect uses a variable, it must be in the list. If you
don't put it in the list, your code might not work right!
Keep the list small: Only put things in the list
that really need to be there. The smaller the list, the faster
your website will be.
In short: The dependency array is how you tell
React exactly when to run your useEffect code. Use it
carefully to keep your website fast and working well!
Example No.4:- Create an web page for a restaurant for
displaying their food items and their todays special dish/recipe
and fetch data from chrome(We can also say that it is not a hard
Page | 53
React JS
coded data). Their must be a button, after clicking that bill page
must be opened with the selected items, price and total price.
This example is similar to Example No.3 but with some
difference.
You just need to change app.jsx and add a new file
fetchdata.js
App.jsx
import "./style/App.css"
import Menu from "./components/Menu";
import Bill from "./Components/Bill";
import { useEffect, useState } from "react";
import request from "./fetchData";
function App(){
const[component, setComponent] = useState("menu")
const[orderedItem, setOrderedItem]=useState([])
const[todo, setTodo] = useState([])
let data = null;
useEffect(function (){
async function fun() {
let data2 = await request();
console.log(data2.todos)
setTodo([...data2.todos])
}
fun();
},[todo]);
return(
<div className="maincontainer">
<h1>Star Restaurant</h1>
<h2> What is new today ??? </h2>
{console.log(todo)}
<ul>
{todo.length===0?
null
:
todo.map((ele)=>{
return <li>{ele.todo}</li>
Page | 54
React JS
})}
</ul>
{component==="menu"?<Menu setComponent={setComponent}
setOrderedItem={setOrderedItem}/>:<Bill
setComponent={setComponent}/>} {/* conditional ternery */}
{/* it displays bill page instead of App page */}
</div>
)
}
// try {
// const response = await fetch(url, options);
Page | 55
React JS
function App(){
// const[page , setPage] = useState('home')
const[component, setComponent] = useState("menu")
const[orderedItem, setOrderedItem]=useState([])
return(
<div className="maincontainer">
<h1>Star Restaurant</h1>
<h3>What Is New Today ??</h3>
{data===null?null:
<div className="recpies">
Name:{data.result.title}
<br></br><br></br>
Ingredients : {data.result.ingredients.map(ele=>{
return <p>{ele.name} <b>{ele.amount}</b></p>
Page | 56
React JS
})}
</div>}
{component==="menu"?<Menu setComponent={setComponent}
setOrderedItem={setOrderedItem}/>:<Bill
setComponent={setComponent}/>} {/* conditional ternery */}
{/* it displays bill page instead of App page */}
</div>
)
}
Page | 57