0% found this document useful (0 votes)
47 views21 pages

FSD Unit 5

The document provides an overview of React, a front-end library developed by Facebook, highlighting its component-based architecture, efficient DOM manipulation through the Virtual DOM, and declarative UI approach. It covers essential concepts such as one-way data binding, React hooks for state management, and seamless integration with backend technologies. Additionally, it explains the structure of a React application, the importance of the Virtual DOM, and the creation and usage of functional and class components.

Uploaded by

s.rajeshgoud2223
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)
47 views21 pages

FSD Unit 5

The document provides an overview of React, a front-end library developed by Facebook, highlighting its component-based architecture, efficient DOM manipulation through the Virtual DOM, and declarative UI approach. It covers essential concepts such as one-way data binding, React hooks for state management, and seamless integration with backend technologies. Additionally, it explains the structure of a React application, the importance of the Virtual DOM, and the creation and usage of functional and class components.

Uploaded by

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

Full Stack Development (MERN)-CS631PE Department of CSE

UNIT-5
Introduction

Why Do We Need React?


React is a powerful front-end library developed by Facebook, designed to create
interactive, efficient, and reusable UI components for web applications. Let’s explore
why React is essential for modern web development.

1. Component-Based Architecture
React encourages the component-based approach, making UI development modular
and scalable.
• Instead of managing entire webpages, React allows breaking down UI into small
reusable components.
• Each component is independent, making debugging and maintenance easier.
Example: Creating a Component
function Greeting(props) {
return <h1>Hello, {props.name}!</h1>;
}
<Greeting name="Sai" />
Here, Greeting is a reusable component that can be used multiple times.

2. Efficient DOM Manipulation (Virtual DOM)


Traditional JavaScript manipulates the Real DOM, which is slow when handling
frequent updates. React uses the Virtual DOM to optimize rendering.
• React compares the Virtual DOM with the previous state and updates only the
changed parts, improving performance.
• This technique reduces unnecessary rendering, leading to a smooth user experience.
Example: Updating State Efficiently
import { useState } from "react";

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

return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
Only the count updates, preventing unnecessary DOM manipulations.

3. Declarative UI
React’s declarative programming model simplifies UI logic.

36
Full Stack Development (MERN)-CS631PE Department of CSE

• Instead of manually managing UI updates, React describes how UI should look based
on data.
• It automatically updates components when data changes.
Example: Conditional Rendering
function UserStatus({ isLoggedIn }) {
return isLoggedIn ? <p>Welcome, Sai!</p> : <p>Please log in.</p>;
}
React automatically re-renders when isLoggedIn state changes.

4. One-Way Data Binding for Predictability


React follows one-way data binding, meaning data flows from parent to child
components.
• This approach ensures predictable behavior and better debugging.
• Reduces complexity compared to traditional two-way data binding used in
frameworks like Angular.
Example: Passing Data from Parent to Child
function Profile({ name }) {
return <p>User: {name}</p>;
}

<Profile name="Sai Kishore" />


The name is passed from the parent component, making data management clear and
structured.

5. React Hooks for State Management


React hooks eliminate the need for class components and allow handling state inside
functional components.
• useState(): Manages component state.
• useEffect(): Handles side effects like fetching data.
Example: Using useEffect() to Fetch Data
import { useState, useEffect } from "react";

function FetchData() {
const [data, setData] = useState([]);

useEffect(() => {
fetch("https://api.example.com/data")
.then(response => response.json())
.then(result => setData(result));
}, []);

return <p>Data: {JSON.stringify(data)}</p>;


}
The component fetches data when mounted, ensuring smooth dynamic updates.

37
Full Stack Development (MERN)-CS631PE Department of CSE

6. Seamless Integration with Backend Technologies


React easily integrates with backend APIs, databases, and other frameworks.
• Works well with Node.js, Express, and RESTful APIs.
• Can be paired with GraphQL for optimized data handling.
Example: Calling an API with React
fetch("https://jsonplaceholder.typicode.com/posts")
.then(response => response.json())
.then(data => console.log(data));

7. Performance Optimization with React Fiber


React's Fiber architecture improves performance by handling UI updates efficiently.
• Supports concurrent rendering for smoother animations and transitions.
• Prioritizes user interactions and minimizes blocking tasks.

8. Strong Community & Ecosystem


React has a huge developer community, providing:
• Thousands of pre-built UI components.
• Extensive documentation and tutorials.
• Continuous updates with cutting-edge features.

Simple React Structure – Explained in Detail

React follows a component-based structure, allowing developers to build modular and


reusable UI elements efficiently. Let’s break down a simple React application step by step.

1. Basic Folder Structure


A typical React app includes the following files and directories:
my-app/
│── src/ # Main source code directory
│ │── components/ # Reusable components
│ │── App.js # Main app component
│ │── index.js # Entry file
│── public/ # Static assets (HTML, images)
│── package.json # Dependency management
│── node_modules/ # Installed packages

2. Entry Point (index.js)


The index.js file serves as the entry point, rendering the React app inside an HTML page.
Code in index.js
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";

38
Full Stack Development (MERN)-CS631PE Department of CSE

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
Explanation:
• ReactDOM.createRoot(document.getElementById("root")): Attaches React to the
HTML element with id "root".
• <App />: The main component that gets rendered.
The root element exists inside public/index.html:
<div id="root"></div>
React injects the entire app inside this div.

3. Main App Component (App.js)


The App.js file defines the root component.
Code in App.js
import React from "react";
import Greeting from "./components/Greeting"; // Import a custom component

function App() {
return (
<div>
<h1>Welcome to My React App</h1>
<Greeting name="Sai Kishore" /> {/* Using the Greeting component */}
</div>
);
}

export default App;


Explanation:
• import React from "react" → React must be imported in every component.
• function App() → A functional component returns JSX (HTML-like syntax).
• <Greeting name="Sai Kishore" /> → A reusable component is used inside App.js.

4. Creating a Reusable Component (Greeting.js)


Components are reusable UI elements.
Code in Greeting.js
import React from "react";

function Greeting(props) {
return <h2>Hello, {props.name}!</h2>;
}

export default Greeting;


Explanation:
• Props (props.name) → Props allow passing values dynamically.
• export default Greeting; → Makes the component available for import.

39
Full Stack Development (MERN)-CS631PE Department of CSE

5. Styling the Components


You can apply styles using CSS files, inline styles, or libraries.
Example: External CSS (App.css)
h1 {
color: blue;
font-family: Arial;
}
Import it inside App.js:
import "./App.css";

6. Running the Application


To start the React app, run:
npm start
This launches the development server at http://localhost:3000.

Understanding the Virtual DOM in React

The Virtual DOM is a key concept in React that enhances performance by efficiently updating
the UI without directly manipulating the actual Real DOM. Let's break it down step by step.

1. What is the Virtual DOM?


The Virtual DOM (VDOM) is a lightweight, in-memory representation of the actual DOM.
React uses this system to optimize UI updates.
Instead of updating the Real DOM directly, React first updates the Virtual DOM, compares
changes, and only updates the necessary parts.
This makes rendering faster and avoids unnecessary DOM manipulations.

2. Difference Between the Real DOM & Virtual DOM


Feature Real DOM Virtual DOM

Updates Slow, directly modifies the UI Fast, modifies an internal representation

Performance Less efficient Highly optimized

Re-rendering Entire DOM tree updates Only the changed components update

Usage Used by traditional browsers Used by React for optimization

3. How the Virtual DOM Works?


React follows a three-step process when updating the UI:
Step 1: Rendering the Virtual DOM
Whenever React components change, React creates a Virtual DOM tree representing the
updated UI.
Step 2: Diffing Algorithm (Comparing Changes)

40
Full Stack Development (MERN)-CS631PE Department of CSE

React compares the new Virtual DOM with the old one using a diffing algorithm.
Step 3: Efficiently Updating the Real DOM
Instead of updating the entire DOM, React replaces only the changed elements, minimizing
performance overhead.

4. Example: How React Updates the Virtual DOM


Let's consider a simple counter component:
import { useState } from "react";

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

return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}

export default Counter;


(How React Works Here)
Initial Render: React creates a Virtual DOM representation of the component.
State Update (count + 1) → React creates a new Virtual DOM reflecting the updated
state.
Diffing Algorithm: React compares changes in the Virtual DOM.
Efficient DOM Update: Instead of updating everything, React only updates the p element
where the count changes.
Result: Faster, efficient updates without modifying the entire DOM structure!

5. Why is the Virtual DOM Important?


• Optimized Rendering → Faster UI updates
• Less Re-rendering → Only affected components update
• Better Performance → Smooth user experience

The Virtual DOM is the backbone of Reacts efficiency, ensuring fast UI updates while
reducing browser workload. This makes React ideal for dynamic applications like
dashboards, social media, and e-commerce sites.

41
Full Stack Development (MERN)-CS631PE Department of CSE

Introducing React Components


React components are the building blocks of a React application. They are
independent, reusable pieces of UI that can be combined to create complex
interfaces.

1. What is a React Component?


A React component is a function or class that returns a piece of UI (written in JSX).
Components allow developers to break down an application into smaller, reusable
parts.
Types of Components:
• Functional Components (recommended) → Simple functions that return JSX.
• Class Components (legacy) → Uses ES6 classes to manage state & lifecycle.

2. Functional Component Example


import React from "react";

function Greeting() {
return <h1>Hello, Sai Kishore! Welcome to React!</h1>;
}

export default Greeting;


Explanation:
• function Greeting() → Defines a functional component.
• JSX (<h1>) → Returns UI elements.
• export default Greeting; → Makes it reusable.
Usage in Another Component (App.js)
import Greeting from "./Greeting";

function App() {
return (
<div>
<Greeting /> {/* Reusing Greeting component */}
</div>
);
}

export default App;

3. Class Component Example (Legacy)


import React, { Component } from "react";

class Welcome extends Component {

42
Full Stack Development (MERN)-CS631PE Department of CSE

render() {
return <h1>Welcome, {this.props.name}!</h1>;
}
}

export default Welcome;


Explanation:
• class Welcome extends Component → Creates a class-based component.
• this.props.name → Uses props for dynamic data.
Usage in Another Component
<Welcome name="Sai Kishore" />

4. Using Props in Components


Props allow data passing between components.
Example: Passing Data Using Props
function UserProfile(props) {
return <p>User: {props.name}, Age: {props.age}</p>;
}

<UserProfile name="Sai Kishore" age={25} />


Props are immutable → Components cannot modify their own props.

5. Using State in Components


State allows components to track changes and update the UI dynamically.
Example: Using useState Hook
import { useState } from "react";

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

return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}

export default Counter;


State changes trigger re-renders → React updates only the modified elements.

6. Combining Components
Multiple components can be combined into a larger UI structure.
Example: Nested Components

43
Full Stack Development (MERN)-CS631PE Department of CSE

function Header() {
return <h1>React App</h1>;
}

function Footer() {
return <footer>Copyright © 2025</footer>;
}

function App() {
return (
<div>
<Header />
<p>Main Content</p>
<Footer />
</div>
);
}

export default App;


Advantages of Components:
• Reusable → Use across multiple pages
• Maintainable → Organized code structure
• Dynamic → Works with props & state

Creating Components in React


In React, components are the building blocks of user interfaces. They allow you to
create reusable UI elements and maintain a clean, modular codebase.
1. Functional Components (Recommended)
Functional components are simple JavaScript functions that return JSX.
function Greeting(props) {
return <h1>Hello, {props.name}!</h1>;
}

export default Greeting;


Props (props.name) → Allow passing data dynamically.
Usage in App.js:

import Greeting from "./Greeting";

function App() {
return <Greeting name="Sai Kishore" />;
}

export default App;

44
Full Stack Development (MERN)-CS631PE Department of CSE

2. Class Components (Legacy)


Class components use the ES6 class syntax and manage state.
import React, { Component } from "react";

class Counter extends Component {


constructor(props) {
super(props);
this.state = { count: 0 };
}

render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Increment
</button>
</div>
);
}
}

export default Counter;


State (this.state.count) → Stores component-specific data.
Event Handling (setState) → Updates the UI dynamically.

Data Flow in React


React follows a unidirectional data flow, meaning data moves in a single direction:
from parent to child components.
1. Props for Parent-to-Child Data Passing
Props allow passing data from a parent to a child component.
Parent Component (App.js):
import Profile from "./Profile";

function App() {
return <Profile name="Sai Kishore" age={25} />;
}

export default App;


Child Component (Profile.js):
function Profile(props) {
return <p>User: {props.name}, Age: {props.age}</p>;
}

45
Full Stack Development (MERN)-CS631PE Department of CSE

export default Profile;


Props are immutable → Child components cannot modify them.

2. State for Local Data Handling


State allows components to manage internal data dynamically.
import { useState } from "react";

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

return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}

export default Counter;


State updates re-render the component automatically.

3. Lifting State Up for Child-to-Parent Communication


Sometimes, a child component needs to update the parent’s state.
Parent Component (App.js):
import { useState } from "react";
import Child from "./Child";

function App() {
const [message, setMessage] = useState("");

return (
<div>
<Child updateMessage={setMessage} />
<p>Message: {message}</p>
</div>
);
}

export default App;


Child Component (Child.js):
function Child({ updateMessage }) {
return <button onClick={() => updateMessage("Hello, Sai!")}>Send
Message</button>;

46
Full Stack Development (MERN)-CS631PE Department of CSE

export default Child;


The child modifies the parent’s state using a function prop.

Rendering and Life Cycle Methods in React – Detailed Explanation


React follows a component lifecycle, which consists of different phases where
components are created, updated, and destroyed. Understanding these lifecycle
methods and the rendering process helps optimize performance and debugging.

1. Rendering in React
Rendering in React is controlled by ReactDOM and occurs when: ✔ A component is
first mounted (initial render).
A component’s state or props change (re-render).
The parent component updates, affecting child components.

2. Initial Render (Mounting Phase)


When a component is first created, React follows these steps:
Example: Mounting a Functional Component
import React from "react";

function Greeting({ name }) {


return <h1>Hello, {name}!</h1>;
}

export default Greeting;


This component renders once when the app starts.
Example: Mounting a Class Component
import React, { Component } from "react";

class Welcome extends Component {


constructor(props) {
super(props);
console.log("Component is mounting...");
}

render() {
return <h1>Welcome, {this.props.name}!</h1>;
}
}

export default Welcome;


The constructor runs once, before rendering.

47
Full Stack Development (MERN)-CS631PE Department of CSE

3. Lifecycle Methods in Class Components


React provides lifecycle methods in class components to control behavior at different
stages.
Mounting Phase (Initial Render)
Method Purpose

constructor() Initializes state & props

render() Returns JSX to display UI

componentDidMount() Executes after the component is added to the DOM

Example of componentDidMount()
class DataFetcher extends Component {
constructor(props) {
super(props);
this.state = { data: null };
}

componentDidMount() {
fetch("https://api.example.com/data")
.then(res => res.json())
.then(result => this.setState({ data: result }));
}

render() {
return <p>Data: {JSON.stringify(this.state.data)}</p>;
}
}
componentDidMount() runs after the first render, making it ideal for fetching data.

4. Updating Phase (Re-rendering)


When state or props change, the component re-renders, triggering update lifecycle
methods.
Method Purpose

shouldComponentUpdate() Controls re-rendering

componentDidUpdate() Runs after re-rendering

render() Renders updated UI

Example: Updating State in a Counter


class Counter extends Component {
constructor(props) {

48
Full Stack Development (MERN)-CS631PE Department of CSE

super(props);
this.state = { count: 0 };
}

componentDidUpdate(prevProps, prevState) {
console.log(`Updated! Previous count: ${prevState.count}`);
}

increment = () => {
this.setState({ count: this.state.count + 1 });
};

render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={this.increment}>Increment</button>
</div>
);
}
}
componentDidUpdate() runs after each state update.

5. Unmounting Phase (Component Removal)


When a component is removed from the DOM, React calls unmount lifecycle
methods.
Method Purpose

componentWillUnmount() Cleans up before removal

Example: Cleanup in componentWillUnmount()


class Timer extends Component {
componentWillUnmount() {
console.log("Component is unmounting...");
clearInterval(this.timer);
}

render() {
return <p>Timer running...</p>;
}
}
Used for cleaning event listeners, timers, and subscriptions.

6. Lifecycle Methods in Functional Components

49
Full Stack Development (MERN)-CS631PE Department of CSE

React hooks provide lifecycle behavior in functional components.


Using useEffect() for Lifecycle Control
import { useState, useEffect } from "react";

function Timer() {
const [time, setTime] = useState(0);

useEffect(() => {
const interval = setInterval(() => setTime(time + 1), 1000);

return () => clearInterval(interval); // Cleanup


}, [time]);

return <p>Time: {time} seconds</p>;


}
useEffect(() => {}, []) runs on mount.
Cleanup functions run before unmounting.

Working with Forms in React


Forms in React allow users to input and submit data, making applications interactive.
React provides controlled components to handle form inputs efficiently.

1. Controlled vs. Uncontrolled Components


React forms can be:
Controlled (recommended) → State manages input values.
Uncontrolled → Use traditional DOM methods (ref) instead.

2. Controlled Components (Recommended)


React controls the form state through useState().
Example: Handling Input in a Form
import { useState } from "react";

function SignupForm() {
const [username, setUsername] = useState("");

return (
<form>
<label>Username:</label>
<input type="text" value={username} onChange={(e) =>
setUsername(e.target.value)} />
<p>Entered: {username}</p>
</form>
);
}

50
Full Stack Development (MERN)-CS631PE Department of CSE

export default SignupForm;


State (username) holds input data.
onChange={(e) => setUsername(e.target.value)} updates state on every keystroke.

3. Handling Multiple Form Inputs


Instead of managing state separately for each field, use one state object.
Example: Managing Multiple Inputs
import { useState } from "react";

function UserForm() {
const [formData, setFormData] = useState({ name: "", email: "" });

const handleChange = (e) => {


setFormData({ ...formData, [e.target.name]: e.target.value });
};

return (
<form>
<input name="name" placeholder="Name" onChange={handleChange} />
<input name="email" type="email" placeholder="Email"
onChange={handleChange} />
<p>Name: {formData.name}, Email: {formData.email}</p>
</form>
);
}

export default UserForm;


Object state (formData) manages multiple inputs dynamically.

4. Handling Form Submission


Forms need to prevent default behavior and process user input.
Example: Submitting a Form
function SubmitForm() {
const [username, setUsername] = useState("");

const handleSubmit = (e) => {


e.preventDefault();
console.log("Submitted:", username);
};

return (
<form onSubmit={handleSubmit}>

51
Full Stack Development (MERN)-CS631PE Department of CSE

<input type="text" value={username} onChange={(e) =>


setUsername(e.target.value)} />
<button type="submit">Submit</button>
</form>
);
}

export default SubmitForm;


onSubmit={(e) => handleSubmit(e)} prevents default form submission.
console.log(username) logs user input.

5. Handling Checkboxes, Radio Buttons, and Select Dropdowns


Forms in React support various input types.
Checkbox Example
function CheckboxExample() {
const [isChecked, setIsChecked] = useState(false);

return (
<label>
<input type="checkbox" checked={isChecked} onChange={(e) =>
setIsChecked(e.target.checked)} />
Accept Terms & Conditions
</label>
);
}

export default CheckboxExample;


Radio Button Example
function GenderForm() {
const [gender, setGender] = useState("");

return (
<form>
<label>
<input type="radio" value="Male" name="gender" onChange={(e) =>
setGender(e.target.value)} />
Male
</label>
<label>
<input type="radio" value="Female" name="gender" onChange={(e) =>
setGender(e.target.value)} />
Female
</label>
<p>Selected Gender: {gender}</p>

52
Full Stack Development (MERN)-CS631PE Department of CSE

</form>
);
}

export default GenderForm;


Dropdown Example
function DropdownExample() {
const [selectedOption, setSelectedOption] = useState("");

return (
<select onChange={(e) => setSelectedOption(e.target.value)}>
<option value="">Choose an option</option>
<option value="React">React</option>
<option value="Node.js">Node.js</option>
</select>
);
}

export default DropdownExample;

6. Validation in Forms
React allows form validation before submission.
Example: Validating Input
function ValidateForm() {
const [email, setEmail] = useState("");
const [error, setError] = useState("");

const handleSubmit = (e) => {


e.preventDefault();
if (!email.includes("@")) {
setError("Invalid email!");
} else {
setError("");
console.log("Valid email:", email);
}
};

return (
<form onSubmit={handleSubmit}>
<input type="email" placeholder="Enter email" onChange={(e) =>
setEmail(e.target.value)} />
<button type="submit">Submit</button>
<p style={{ color: "red" }}>{error}</p>
</form>

53
Full Stack Development (MERN)-CS631PE Department of CSE

);
}

export default ValidateForm;

Routing in React
Routing in React allows users to navigate between different views or pages without
reloading the entire application. It is efficiently managed using the React Router library.

1. Why Do We Need Routing?


Single-page applications (SPAs) need multiple views without reloading.
Improves user experience by handling navigation smoothly.
Helps load dynamic content without losing state.

2. Installing React Router


To add routing functionality, install react-router-dom:
npm install react-router-dom

3. Basic Routing Setup


The following example demonstrates a simple routing setup.
App.js (Main Component)
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import Home from "./Home";
import About from "./About";

function App() {
return (
<Router>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</Router>
);
}

export default App;


<Router> → Defines the routing system.
<Routes> → Holds all the possible routes.
<Route path="/" element={<Home />}/> → Maps path / to the Home component.

54
Full Stack Development (MERN)-CS631PE Department of CSE

4. Creating Component Pages


Home.js
function Home() {
return <h1>Welcome to the Home Page!</h1>;
}

export default Home;


About.js
function About() {
return <h1>About Us Page</h1>;
}

export default About;

5. Adding Navigation Links


Use Link to navigate between pages.
Example: Navbar
import { Link } from "react-router-dom";

function Navbar() {
return (
<nav>
<Link to="/">Home</Link> | <Link to="/about">About</Link>
</nav>
);
}

export default Navbar;


<Link to="/about">About</Link> → Prevents full-page reload.
Uses client-side routing for a faster experience.

6. Handling 404 Pages


If an invalid URL is accessed, a fallback 404 page can be set.
Example: Adding a "Not Found" Route
function NotFound() {
return <h1>404 - Page Not Found</h1>;
}

<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="*" element={<NotFound />} /> {/* Handles unmatched routes */}
</Routes>

55
Full Stack Development (MERN)-CS631PE Department of CSE

7. Route Parameters for Dynamic Pages


Route parameters allow dynamic content based on the URL.
Example: Dynamic Profile Page
Route Setup (App.js)
<Route path="/profile/:username" element={<Profile />} />
Profile Component (Profile.js)
import { useParams } from "react-router-dom";

function Profile() {
const { username } = useParams();
return <h1>Welcome, {username}!</h1>;
}

export default Profile;

56

You might also like