FSD Unit 5
FSD Unit 5
UNIT-5
Introduction
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.
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.
function FetchData() {
const [data, setData] = useState([]);
useEffect(() => {
fetch("https://api.example.com/data")
.then(response => response.json())
.then(result => setData(result));
}, []);
37
Full Stack Development (MERN)-CS631PE Department of CSE
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.
function App() {
return (
<div>
<h1>Welcome to My React App</h1>
<Greeting name="Sai Kishore" /> {/* Using the Greeting component */}
</div>
);
}
function Greeting(props) {
return <h2>Hello, {props.name}!</h2>;
}
39
Full Stack Development (MERN)-CS631PE Department of CSE
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.
Re-rendering Entire DOM tree updates Only the changed components update
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.
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
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
function Greeting() {
return <h1>Hello, Sai Kishore! Welcome to React!</h1>;
}
function App() {
return (
<div>
<Greeting /> {/* Reusing Greeting component */}
</div>
);
}
42
Full Stack Development (MERN)-CS631PE Department of CSE
render() {
return <h1>Welcome, {this.props.name}!</h1>;
}
}
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
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>
);
}
function App() {
return <Greeting name="Sai Kishore" />;
}
44
Full Stack Development (MERN)-CS631PE Department of CSE
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Increment
</button>
</div>
);
}
}
function App() {
return <Profile name="Sai Kishore" age={25} />;
}
45
Full Stack Development (MERN)-CS631PE Department of CSE
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
function App() {
const [message, setMessage] = useState("");
return (
<div>
<Child updateMessage={setMessage} />
<p>Message: {message}</p>
</div>
);
}
46
Full Stack Development (MERN)-CS631PE Department of CSE
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.
render() {
return <h1>Welcome, {this.props.name}!</h1>;
}
}
47
Full Stack Development (MERN)-CS631PE Department of CSE
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.
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.
render() {
return <p>Timer running...</p>;
}
}
Used for cleaning event listeners, timers, and subscriptions.
49
Full Stack Development (MERN)-CS631PE Department of CSE
function Timer() {
const [time, setTime] = useState(0);
useEffect(() => {
const interval = setInterval(() => setTime(time + 1), 1000);
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
function UserForm() {
const [formData, setFormData] = useState({ name: "", email: "" });
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>
);
}
return (
<form onSubmit={handleSubmit}>
51
Full Stack Development (MERN)-CS631PE Department of CSE
return (
<label>
<input type="checkbox" checked={isChecked} onChange={(e) =>
setIsChecked(e.target.checked)} />
Accept Terms & Conditions
</label>
);
}
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>
);
}
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>
);
}
6. Validation in Forms
React allows form validation before submission.
Example: Validating Input
function ValidateForm() {
const [email, setEmail] = useState("");
const [error, setError] = useState("");
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
);
}
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.
function App() {
return (
<Router>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</Router>
);
}
54
Full Stack Development (MERN)-CS631PE Department of CSE
function Navbar() {
return (
<nav>
<Link to="/">Home</Link> | <Link to="/about">About</Link>
</nav>
);
}
<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
function Profile() {
const { username } = useParams();
return <h1>Welcome, {username}!</h1>;
}
56