0% found this document useful (0 votes)
9 views35 pages

FSD Unit 5

React is a JavaScript library developed by Facebook for building dynamic web applications and single-page applications (SPAs) using a component-based approach, which enhances performance through its Virtual DOM. Components are reusable pieces of UI that simplify development, testing, and maintenance, allowing for better organization and collaboration among developers. The structure of a React application typically includes a root component, child components, and a main HTML file, making it easy to build and scale applications.
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)
9 views35 pages

FSD Unit 5

React is a JavaScript library developed by Facebook for building dynamic web applications and single-page applications (SPAs) using a component-based approach, which enhances performance through its Virtual DOM. Components are reusable pieces of UI that simplify development, testing, and maintenance, allowing for better organization and collaboration among developers. The structure of a React application typically includes a root component, child components, and a main HTML file, making it easy to build and scale applications.
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/ 35

� Topic 1: Need of React

✅ Why Do We Need React?

React is a JavaScript library made by Facebook to solve real problems developers face when building
dynamic websites and single-page applications (SPAs).
Traditional websites reload the whole page whenever something changes — this feels slow and old-
fashioned. React solves this by letting developers build apps that update parts of the page instantly
without a full reload.

React uses a component-based approach, which means the UI is split into small, reusable blocks called
components.
Each component has its own logic and layout — this makes it easy to build, test, and reuse pieces across
big projects.

Another big reason for using React is its Virtual DOM.


Updating the real DOM again and again is slow. React first creates a virtual copy of the DOM, finds
exactly what changed, and updates only that part — this makes apps much faster.

React is also declarative — instead of writing instructions step by step, you write what the UI should
look like, and React takes care of changing it.
This makes code easier to read, debug, and maintain.

React works well for single-page applications that need fast updates — like Facebook, Instagram, and
Netflix.
It also has a huge community and many tools, so it’s easy to find help, learn, and build professional apps.

React’s ideas work across platforms too. You can use React Native to build mobile apps for Android and
iOS using the same React concepts — saving time and effort.

✅ One Simple Example

A tiny React component:

import React from 'react';

function Welcome() {

return <h2>Welcome to React!</h2>;

export default Welcome;

This shows how small and reusable React components are — you can use <Welcome /> anywhere in
your app to display the same message.
✅ Conclusion

React is needed because it helps developers build fast, dynamic, and maintainable web applications.
It saves time, keeps code clean, and makes complex UIs easier to handle with components, Virtual DOM,
and declarative syntax — all backed by a big community.

� Topic 2: Simple React Structure

✅ What Is a Simple React Structure?

Every React application has a basic structure that helps developers organize their code.
React uses a component-based design — the whole UI is broken into small parts (components).

A simple React app has:

 A root component → usually App.js

 One or more child components

 A main HTML file → usually index.html in public/

 An entry point JS file → usually index.js in src/

✅ How React Structure Works

1⃣ index.html
This is the main HTML page with a <div> with an id like root.
React renders your entire app inside this div.

2⃣ index.js
This is the main JS file. It imports React, the App component, and tells React to render App inside the
root div.

3⃣ App.js
This is the root component. You write your UI here using JSX.
You can break the UI into smaller child components.

✅ Folder Structure Example

my-app/

├── public/

│ └── index.html
├── src/

│ ├── index.js

│ ├── App.js

│ ├── components/

│ │ └── Hello.js

✅ One Simple Code Example

index.js

import React from 'react';

import ReactDOM from 'react-dom';

import App from './App';

ReactDOM.render(<App />, document.getElementById('root'));

App.js

import React from 'react';

function App() {

return <h2>My First React Structure</h2>;

export default App;

✅ How It Runs

 ReactDOM.render puts <App /> inside the root div.

 App returns JSX which shows the UI.

 If you add more components, App combines them together.

✅ Why Use This Structure

✔ Keeps code organized.


✔ Easy to reuse components.
✔ Clear separation between HTML template (index.html) and React logic (index.js & App.js).

✅ Conclusion
A simple React structure always has:

 One HTML page,

 One entry JS file,

 One root component,

 And any number of child components.

This makes React apps easy to build, scale, and maintain!

� Topic 4: Components in React

✅ What Are Components?

Components are the heart of React.


A component is a small, independent, reusable piece of the user interface.
In React, everything you build is made up of components — a webpage, a form, a button, or even a
whole section like a header or footer.

The idea is simple:


� Break the UI into smaller parts.
� Each part works by itself.
� Combine parts to build complex pages.

For example, a simple website might have:

 A HeaderComponent for the site logo and navigation.

 A SidebarComponent for menus.

 A ContentComponent for the main text.

 A FooterComponent for contact info.

All these are separate components that together make up one big parent component, usually called App.

✅ Why Do We Use Components?

React introduced the component-based model to make big apps easy to build and maintain.

✔ Reusability:
Once you build a component, you can use it anywhere.
For example, a Button component can be used on the home page, login page, or contact page.
✔ Separation of Concerns:
Each component handles its own HTML, CSS, and JavaScript logic.
This makes it easy to test and debug

✔ Faster Development:
Multiple developers can work on different components at the same time without conflict.

✔ Easy to Update:
If a feature changes, you only update that one component — no need to touch the whole project.

✅ Types of Components

React has two main types:

1⃣ Functional Components:
These are the most common today.
They are simple JavaScript functions that return JSX.

2⃣ Class Components:
These are ES6 classes that extend React.Component.
They can hold state and lifecycle methods.

Since React 16.8, functional components with Hooks can also handle state, so most developers prefer
functional ones now.

✅ Example of Functional Component

import React from 'react';

function Welcome(props) {

return <h2>Hello, {props.name}!</h2>;

export default Welcome;

Here, Welcome is a functional component that takes a name and displays it.

✅ Example of Class Component

import React, { Component } from 'react';

class Welcome extends Component {

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

export default Welcome;

Both do the same thing but use different syntax.

✅ Using Components

To use a component inside another, write its custom HTML tag:

<Welcome name="Harika" />

React passes data to components using props (short for properties).

✅ Props: Passing Data to Components

Props let you make components dynamic.


They are like function parameters — they pass info from a parent component to a child.

Example: A Profile component might get name, age, email as props and show them.

Props are read-only — you cannot change them inside the component

✅ Components and State

Apart from props, components can also have state.


State means data that can change over time — like form inputs, toggles, or counters.

In functional components, you use Hooks (like useState) to handle state.

✅ Combining Components

A React app usually has:

 A root component (App).

 Many child components (Header, Footer, Sidebar).

 Components nest inside each other

Example:

function App() {

return (
<div>

<Header />

<Content />

<Footer />

</div>

);

✅ Key Benefits

✔ Reusable → Use anywhere.


✔ Isolated → One bug won’t break the whole app.
✔ Testable → Easier to write unit tests.
✔ Easy to maintain → Makes teamwork smooth.

✅ Conclusion

Components are the backbone of React.


They make it possible to build modern web apps that are modular, reusable, and scalable.
Understanding how to create and use components is the first step to becoming a good React developer!

✅ � Topic 3: The Virtual DOM

✅ What is the Virtual DOM?

 In React, the Virtual DOM is one of the most important reasons why React is fast and efficient
compared to traditional web development.
DOM stands for Document Object Model — it is a programming interface that represents the
structure of a web page.
When you open a website, the browser turns the HTML into the DOM so it can render the page
on the screen.
 In a normal web app, every time something changes — like typing in a form or clicking a button
— the real DOM has to update.
But updating the real DOM can be slow, especially if there are many changes at once.
This is where React’s Virtual DOM makes a big difference.

✅ How the Virtual DOM Works


 The Virtual DOM is a lightweight copy of the real DOM that React keeps in memory.
When something in the app changes, React does not update the real DOM directly.
Instead, it updates the Virtual DOM first.
 React then compares the old Virtual DOM and the new Virtual DOM using a process called
diffing.
It looks for the differences and figures out exactly what has changed.
After that, React updates only the changed parts of the real DOM — not the entire page.
 This makes updates fast and efficient because updating a small part of the DOM is much quicker
than reloading or rewriting the whole page.

✅ Why Use the Virtual DOM?

✔ Better performance: Fewer changes to the real DOM means faster updates.
✔ Smooth user experience: Changes appear instantly without flickering or delays.
✔ Cleaner code: Developers don’t have to manually figure out which part of the DOM to update —
React handles that automatically.
✔ Easier maintenance: You focus on what the UI should look like, not how to update it step by step.

✅ How Diffing and Reconciliation Work

When React detects changes in your component’s state or props, it:


1⃣ Creates a new Virtual DOM tree.
2⃣ Compares (diffs) it with the previous Virtual DOM tree.
3⃣ Finds the minimal set of changes (called a “patch”).
4⃣ Updates the real DOM only where needed.

This process is called Reconciliation — it ensures your UI stays in sync with your data in the fastest
possible way.

✅ One Simple Example

import React, { useState } from 'react';

function Counter() {

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

return (

<div>

<h2>Count: {count}</h2>

<button onClick={() => setCount(count + 1)}>Add</button>


</div>

);

export default Counter;

Here:

 When you click Add, React changes the count in the state.

 React updates the Virtual DOM first.

 It compares the old and new Virtual DOM.

 It finds that only the number changed.

 It updates only the <h2> in the real DOM — not the whole page!

✅ Virtual DOM vs Real DOM

Virtual DOM Real DOM

Lightweight copy in memory Actual structure in the browser

Fast updates Slower to update directly

Uses diffing Updates everything

Only changed parts rendered Full re-renders may be needed

✅ Key Points

✔ Virtual DOM makes React apps fast and responsive.


✔ Developers don’t need to manage the real DOM directly.
✔ React’s smart diffing and patching save time and boost performance.

✅ Conclusion

The Virtual DOM is what makes React different from many other libraries.
By using this smart in-memory copy, React can quickly find what changed and update only what’s
needed — giving users a smooth, high-performance experience.

� Topic 5: Introducing React Components

✅ What Are React Components?


 A React Component is the basic building block of a React application.
Everything you see on a React website — from a single button to an entire page layout — is
made using components.
 A component in React is like a JavaScript function or class that returns JSX — the HTML-like
code you write inside JavaScript.
React then converts this JSX into actual HTML that the browser displays.

The main idea behind components is “divide and conquer.”


Instead of writing all your HTML in one long file, you break your UI into small, reusable parts, each with
its own purpose.

✅ Why Do We Use Components?

✔ Reusability: Once you make a component, you can reuse it anywhere in your project.
✔ Readability: Breaking the UI into parts makes your code easier to read and manage.
✔ Maintainability: If something changes, you update only that part — not the whole app.
✔ Teamwork: Multiple developers can work on different components at the same time.

✅ How to Define a React Component

There are two main ways to define a component in React:


1⃣ Functional Components
2⃣ Class Components

✅ Functional Components:
A functional component is simply a JavaScript function that returns JSX.

Example:

function Greeting() {

return <h2>Hello, welcome to React!</h2>;

These are the most common today because they are simple and easy to write.

✅ Class Components:
A class component is an ES6 class that extends React.Component and has a render() method.

Example:

import React, { Component } from 'react';

class Greeting extends Component {


render() {

return <h2>Hello, welcome to React!</h2>;

Before React Hooks were introduced, only class components could handle state and lifecycle methods.
Today, functional components can do everything class components can do — so most developers prefer
the functional style.

✅ How Do Components Work Together?

A React app usually has:

 A root component (often called App).

 Many child components inside it.

The root component organizes the entire UI by combining these child components.

Example:

function App() {

return (

<div>

<Header />

<Content />

<Footer />

</div>

);

Here, <Header />, <Content />, and <Footer /> are all separate components that the root App puts
together.

✅ Props: Making Components Dynamic

Components can receive data through props.


Props allow the parent component to customize what each child shows.
For example:

function Greeting(props) {

return <h2>Hello, {props.name}!</h2>;

<Greeting name="Harika" />

<Greeting name="Rahul" />

Here, the same Greeting component displays different names based on the props.

✅ Component Naming Rules

✔ Component names must start with a capital letter.


✔ The file name usually matches the component name.
✔ Use the .jsx or .js file extension.
✔ Export the component so other files can import and use it.

✅ One Simple Example

Below is a simple functional component in React:

import React from 'react';

function Welcome() {

return <h2>Welcome to My First React Component!</h2>;

export default Welcome;

When you use <Welcome /> inside your App component, it displays the message.

✅ Best Practices

✔ Keep components small and focused — one piece of UI per component.


✔ Give components meaningful names that explain what they do.
✔ Use props to pass data instead of repeating similar code.
✔ Break big components into smaller sub-components if needed.

✅ Key Points

 React apps are built by combining many small components.


 Components can be functional or class-based, but functional is preferred today.

 Components make React apps easy to build, maintain, and scale.

✅ Conclusion

Introducing React components is the first step to learning React.


They help developers write clean, reusable, and dynamic UI code.
Mastering how to build and connect components is essential for any React project!

� Topic 6: Creating Components in React

✅ What Does It Mean to Create Components?

In React, creating components means building small, reusable blocks of UI that together make up your
whole application.

React does not work like old HTML pages where you write all your code in a single file.
Instead, you break the UI into components and combine them to build pages.

Example: A shopping site might have:

 A Header component (logo, search bar)

 A ProductList component (shows items)

 A ProductCard component (for each product)

 A Cart component (shopping cart)

 A Footer component (contact info)

Each piece is its own component, and React combines them all.

✅ Ways to Create a Component

React lets you create components in two ways:


1⃣ Functional Components (modern, easy)
2⃣ Class Components (older, still used)

✅ Creating a Functional Component

A functional component is a JavaScript function that returns JSX.

Example:

function Welcome() {
return <h2>Hello, React!</h2>;

You can also use an arrow function:

const Welcome = () => <h2>Hello, React!</h2>;

Functional components are:


✔ Shorter to write
✔ Easy to read
✔ Preferred in modern React because they work with Hooks (like useState and useEffect).

✅ Creating a Class Component

A class component uses an ES6 class that extends React.Component.

Example:

import React, { Component } from 'react';

class Welcome extends Component {

render() {

return <h2>Hello, React!</h2>;

export default Welcome;

Class components can also have state and lifecycle methods.


However, most new React code uses functional components because Hooks give functional components
the same power.

✅ Steps to Create a Component

✔ 1⃣ Create a new file — e.g., Welcome.js


✔ 2⃣ Write your function or class that returns JSX.
✔ 3⃣ Export the component using export default.
✔ 4⃣ Import and use it inside your root component (App.js).

✅ Combining Components

Once you create a component, you can import and use it like a custom HTML tag.
Example in App.js:

import Welcome from './Welcome';

function App() {

return (

<div>

<Welcome />

</div>

);

This shows <h2>Hello, React!</h2> from your Welcome component.

✅ Passing Props

Components can also receive props (properties).


Props make a component dynamic by letting you pass data to it.

Example:

function Welcome(props) {

return <h2>Hello, {props.name}!</h2>;

In App.js:

<Welcome name="Harika" />

Output: Hello, Harika!

✅ Organizing Components

Big React apps have many files and folders to keep things organized:

/src

├── App.js

├── components/

│ ├── Header.js
│ ├── Footer.js

│ ├── ProductCard.js

Keeping each component in its own file makes it easy to manage.

✅ One Simple Example

Here’s a clear mini project example: a Greeting component.

Greeting.js

import React from 'react';

function Greeting() {

return <h3>Welcome to My React App!</h3>;

export default Greeting;

App.js

import React from 'react';

import Greeting from './Greeting';

function App() {

return (

<div>

<Greeting />

</div>

);

export default App;

✅ This shows how you:

 Create a component (Greeting).

 Export it.
 Import it in App.

 Use <Greeting /> like an HTML tag.

✅ Best Practices

✔ Start component names with a capital letter.


✔ Keep each component focused on one job.
✔ Store related components in a components folder.
✔ Use functional components with Hooks for new projects.

✅ Conclusion

Creating components in React is the foundation of building any React app.


You split your UI into small, reusable parts, keep your code organized, and make your pages dynamic
and easy to maintain.
This is why learning how to create and use components is the first big skill for any React developer.

� Topic 7: Data and Data Flow in React

✅ Why Is Data Important in React?

In React, data is what makes web apps dynamic and interactive.


Data can come from many places — user input, APIs, or other parts of your app.
How you store, pass, and update this data is very important for building apps that work correctly.

React follows a clear principle for handling data:


� Unidirectional (one-way) data flow.

This means data flows in one direction only — from parent components to child components.

✅ How Data Flows in React

In React:

 The parent component holds the main data.

 The parent passes data down to child components using props.

 Child components receive props but cannot change them directly

This makes your app predictable and easy to debug, because you always know where the data comes
from.
Example:
A parent App component holds a user name.
It passes the name as a prop to a Greeting child component.

✅ Props: Passing Data Down

Props are the main way to send data from parent to child.

Example:

function App() {

return <Greeting name="Harika" />;

function Greeting(props) {

return <h2>Hello, {props.name}!</h2>;

Here:

 App passes name="Harika" to Greeting.

 Greeting displays it using {props.name}.

Key point: The child cannot change props.


If you want to change the name, you must change it in the parent.

✅ State: Managing Local Data

While props are used for passing data, state is used for storing and changing data inside a component.

For example:

 A counter value.

 A user’s input in a form.

 Whether a menu is open or closed.

Functional components use the useState Hook to create and update state.

Example:

import React, { useState } from 'react';


function Counter() {

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

return (

<div>

<h3>Count: {count}</h3>

<button onClick={() => setCount(count + 1)}>Add</button>

</div>

);

Here:

 count is state.

 setCount is a function to update it.

 When the button is clicked, count increases and React re-renders the UI.

✅ Combining Props and State

A common React pattern:

 Use state in parent components to store data that can change.

 Use props to pass that data down to child components for display.

Example:

function App() {

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

return <Greeting name={userName} />;

✅ Why Unidirectional Data Flow Matters

One-way data flow:


✔ Keeps your app predictable.
✔ Makes it easier to find bugs.
✔ Makes components reusable — they don’t depend on global data.
✔ Follows the React design philosophy — small, testable parts.

✅ What If Child Needs to Change Parent’s Data?

Sometimes, a child needs to send data back — for example, a form input.

React solves this using callback functions:

 The parent passes a function as a prop.

 The child calls this function to send data back.

Example:

function App() {

const [name, setName] = useState('');

function updateName(newName) {

setName(newName);

return <InputComponent onNameChange={updateName} />;

function InputComponent(props) {

return (

<input

type="text"

onChange={(e) => props.onNameChange(e.target.value)}

/>

);

✅ Key Points

 Props pass data down.


 State stores local, changeable data.

 Data flows one way — from parent to child.

 Use callbacks if child must send data up.

✅ Conclusion

React’s simple, one-way data flow makes apps easy to understand, debug, and grow.
Combining state and props the right way lets you build dynamic apps that are organized, fast, and
maintainable.

� Topic 8: Rendering and Life Cycle Methods in React

✅ What Does Rendering Mean in React?

In React, rendering means displaying your app’s UI on the screen.


React uses components that return JSX — which looks like HTML — and then React turns that JSX into
real DOM elements that the browser can show to the user.

Every time your app’s state or props change, React automatically re-renders the affected components.
This means the UI always stays up to date with your data — without you manually updating the DOM
yourself.

Example: If you have a counter and you increase its value, React updates only the part of the page that
shows the number, not the whole page.
This is possible because of React’s Virtual DOM, which finds what changed and updates only that part.

✅ How Rendering Works

A React app has:

 One root component (usually App.js).

 This root component returns JSX.

 React renders this JSX inside a <div> in index.html (like <div id="root">).

When you run ReactDOM.createRoot(...).render(<App />), React:


1⃣ Loads the root component.
2⃣ Converts its JSX to real HTML.
3⃣ Shows it inside the root div.

If your data changes — for example, a user types in a text box — React re-renders only the parts that
changed.
✅ Why Is Rendering Important?

✔ Makes your app dynamic and interactive.


✔ Keeps the page in sync with your data.
✔ Avoids full page reloads — only parts of the page change.
✔ Saves time and improves performance.

✅ What Are Life Cycle Methods?

Life Cycle Methods are special functions you can use in class components to run code at different points
of a component’s life.

Every React component goes through a life cycle:

 Mounting: The component is created and added to the DOM.

 Updating: The component updates because props or state changed.

 Unmounting: The component is removed from the DOM.

Life cycle methods let you run custom code when these things happen.

✅ Important Life Cycle Methods

In class components, the main life cycle methods are:

1⃣ constructor()

 Runs once, when the component is created.

 Used for setting initial state.

2⃣ render()

 Required.

 Returns the JSX to display.

3⃣ componentDidMount()

 Runs once, right after the component is mounted on the screen.

 Good for API calls, fetching data, setting up timers.

4⃣ componentDidUpdate()

 Runs every time the component’s props or state change.


 Good for reacting to changes, like saving data.

5⃣ componentWillUnmount()

 Runs just before the component is removed from the screen.

 Good for cleaning up — for example, clearing timers or removing event listeners

✅ Life Cycle Methods in Functional Components

Modern React uses Hooks to handle life cycle behavior in functional components.

✅ The useEffect Hook does the job of componentDidMount, componentDidUpdate, and


componentWillUnmount all in one.

Example:

import React, { useState, useEffect } from 'react';

function Timer() {

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

useEffect(() => {

console.log('Component Mounted or Updated');

return () => {

console.log('Component Unmounted');

};

}, [count]); // Runs when count changes

return (

<div>

<h3>Count: {count}</h3>

<button onClick={() => setCount(count + 1)}>Add</button>

</div>

);

✅ Key Points
✔ Rendering is how React shows your UI on screen.
✔ React’s Virtual DOM makes rendering fast and efficient.
✔ Life cycle methods let you run extra code during mounting, updating, and unmounting.
✔ Today, functional components use Hooks (useEffect) for life cycle logic.

✅ Conclusion

Understanding rendering and life cycle methods helps you build React apps that are dynamic, fast, and
able to handle real-world tasks like fetching data, updating the page, and cleaning up resources when a
component is removed.

� Topic 9: Working with Forms in React

✅ What Are Forms in React?

Forms are an important part of any web application.


They let users enter information — like usernames, passwords, comments, or search queries — and
send that information to the app.

In plain HTML, you use <form>, <input>, <textarea>, and <button> elements.
In React, you still use these same elements, but you handle the data differently using state.

✅ How Forms Work in React

In React, you make controlled components.


This means:

 The form elements get their current values from React state.

 When the user types, React updates the state.

 The updated state changes the form input’s value.

So, the React component controls the form, not the browser’s default behavior.

✅ Why Use Controlled Components?

✔ Keeps form data in React state, so you always know what the current values are.
✔ Makes it easier to validate user input.
✔ Makes it easy to handle submit actions.
✔ Keeps all your app’s data flow in one place, instead of mixing with the DOM.

✅ Basic Example of a Controlled Input

import React, { useState } from 'react';


function NameForm() {

const [name, setName] = useState('');

function handleChange(e) {

setName(e.target.value);

function handleSubmit(e) {

e.preventDefault();

alert('Hello, ' + name);

return (

<form onSubmit={handleSubmit}>

<label>

Name:

<input type="text" value={name} onChange={handleChange} />

</label>

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

</form>

);

export default NameForm;

✅ How this works:

 The input’s value is controlled by name (state).

 When the user types, handleChange updates name.

 When the user clicks Submit, handleSubmit shows an alert.


 e.preventDefault() stops the page from reloading.

✅ Handling Multiple Inputs

In real forms, you often have more than one input.


You can handle this by using one state object.

Example:

const [formData, setFormData] = useState({ username: '', email: '' });

function handleChange(e) {

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

✅ Here, [e.target.name] updates the correct field in the state.

✅ Using Textareas and Selects

In React, <textarea> and <select> are also controlled the same way.

Example:

<textarea value={comment} onChange={handleCommentChange} />

<select value={selectedOption} onChange={handleSelectChange}>

<option value="option1">Option 1</option>

</select>

✅ Validating Form Data

Since form values are stored in state, you can easily check the values when the form is submitted.

Example:

function handleSubmit(e) {

e.preventDefault();

if (name.trim() === '') {

alert('Name is required!');

return;

}
// Continue...

✅ Uncontrolled Components

While React recommends controlled components, you can also make uncontrolled components, which
use the DOM to store values instead of React state.

Example:

const inputRef = useRef();

function handleSubmit(e) {

e.preventDefault();

alert(inputRef.current.value);

return <input ref={inputRef} />;

✅ But this is less common — controlled components are preferred because they follow React’s one-
way data flow.

✅ Why Forms in React Are Special

In regular HTML:

 The browser handles the input value by itself.

In React:

 The input’s value is stored in React state.

 You have full control to check, change, and submit that data exactly how you want.

✅ Best Practices

✔ Use controlled components for all forms.


✔ Store form data in state.
✔ Use onChange handlers to update state as the user types.
✔ Use onSubmit handlers to handle form submissions.
✔ Validate data before submitting.

✅ Key Points
 React forms use controlled components.

 The form’s data is stored in state.

 The user’s input updates the state, and the state updates the input’s value.

 This makes React forms predictable and easy to manage.

✅ Conclusion

Working with forms in React is a key skill.


By using controlled components, you keep your data and UI in sync, handle user input properly, and
build forms that are dynamic, interactive, and easy to validate.

� Topic 10: Integrating Third Party Libraries in React

✅ What Are Third Party Libraries?

In web development, third party libraries are pre-written pieces of code made by other developers or
companies.
They help you add features faster, without having to build everything from scratch.

React is a library for building user interfaces — but it does not include everything by default.
Sometimes you need extra features like:

 Routing and navigation

 Form validation

 Charts and graphs

 HTTP requests

 Animations

For these tasks, developers use third party libraries that work well with React.

✅ Why Use Third Party Libraries in React?

✔ Saves time: You don’t need to build complex features yourself.


✔ Reliable: Many popular libraries are well-tested by thousands of developers.
✔ Community Support: Easier to find help, tutorials, and solutions online.
✔ Keeps your code clean: Use ready-made tools instead of writing extra code.

✅ Common Third Party Libraries in React


Here are a few libraries React developers often use:

1⃣ React Router:
Used for adding routing and navigation in single-page apps.
Example: Switching between Home, About, and Contact pages without reloading the entire page.

2⃣ Axios or Fetch:
Used for making HTTP requests (API calls).
Example: Getting user data from a server.

3⃣ Formik or React Hook Form:


Used for easier form handling and validation.

4⃣ Lodash:
A utility library with helpful functions for working with arrays, objects, and strings.

5⃣ Chart.js or Recharts:
Used for adding charts, graphs, or data visualizations.

✅ How to Install a Third Party Library

Most libraries are installed using npm (Node Package Manager) or yarn.

Example:

npm install axios

or

yarn add axios

This adds the library to your node_modules folder so you can import and use it in your React app.

✅ How to Use a Third Party Library in React

You use import to bring the library into your component.

Example:

import axios from 'axios'

function GetData() {

// Use axios here

✅ One Practical Example: Using Axios


Here’s a simple example showing how to use Axios to get data from an API.

import React, { useState, useEffect } from 'react';

import axios from 'axios';

function UserList() {

const [users, setUsers] = useState([]);

useEffect(() => {

axios.get('https://jsonplaceholder.typicode.com/users')

.then(response => setUsers(response.data))

.catch(error => console.error(error));

}, []);

return (

<div>

<h2>User List</h2>

<ul>

{users.map(user => <li key={user.id}>{user.name}</li>)}

</ul>

</div>

);

export default UserList;

✅ How it works:

 axios.get() makes a GET request to an API.

 When data is received, it updates users state.

 React renders the list of user names.

 The page does not reload — React updates the UI automatically.


✅ Things to Keep in Mind

✔ Always read the documentation for each library to learn how to use it properly.
✔ Install only trusted, well-maintained libraries.
✔ Keep your dependencies updated to avoid security issues.
✔ Only add libraries when you really need them — too many can slow down your app.

✅ Where Do You Import Libraries?

You usually import libraries:

 At the top of your React component file.

 Sometimes in a helper file if the logic is shared by many components.

Example:

import _ from 'lodash'; // Import Lodash

import { BrowserRouter, Route } from 'react-router-dom'; // Import React Router

✅ Examples of Other Libraries

 React Bootstrap: Add ready-made UI components like modals, tooltips, buttons.

 Moment.js: Work with dates and times easily.

 Redux: Manage complex global state.

✅ Key Points

 React is powerful but does not include every feature by default.

 Third party libraries help you build better apps faster.

 Always install, import, and use libraries the React way.

 Keep your app clean and lightweight — don’t add libraries you don’t really need.

✅ Conclusion

Integrating third party libraries in React makes your app more powerful, saves time, and gives you
access to tools built by experts.
It’s an important skill for every React developer — because real-world projects often rely on multiple
libraries to build modern, user-friendly apps.
� Topic 11: Routing in React

✅ What is Routing in React?

When you build a single-page application (SPA) with React, all your content loads on one HTML page.
But users still expect to navigate between different pages like Home, About, Contact, etc. — without
reloading the whole page.

Routing is how you let users move between pages smoothly, while React loads and displays different
components based on the URL.

React itself does not include routing by default — instead, developers use a popular third-party library
called React Router.

✅ What is React Router?

React Router is the standard library for adding routing to React apps.
It lets you:

 Define routes (URLs).

 Tell React which component to show for each route.

 Change the URL without reloading the entire page.

 Make apps feel like real websites with multiple pages.

✅ How Does Routing Work in React?

When a user clicks a link, React Router:


1⃣ Updates the URL in the browser (e.g., /about).
2⃣ Prevents the browser from doing a full reload.
3⃣ Finds the matching route in your app.
4⃣ Loads and shows the component for that route.

All of this happens instantly and feels smooth.

✅ Main Parts of React Router

React Router uses a few key components:

✔ BrowserRouter
Wraps your entire app and keeps track of the URL.

✔ Routes
A container for all your Route components.
✔ Route
Defines a path (URL) and tells React which component to show.

✔ Link
Used to create links that change the URL without reloading the page.

✅ How to Install React Router

Install React Router with npm or yarn:

npm install react-router-dom

✅ Basic Example of Routing

Here’s a simple example of a React app with three pages: Home, About, and Contact.

1⃣ App.js

import React from 'react';

import { BrowserRouter, Routes, Route, Link } from 'react-router-dom';

import Home from './Home';

import About from './About';

import Contact from './Contact'

function App() {

return (

<BrowserRouter>

<nav>

<Link to="/">Home</Link> | {' '}

<Link to="/about">About</Link> | {' '}

<Link to="/contact">Contact</Link>

</nav

<Routes>

<Route path="/" element={<Home />} />

<Route path="/about" element={<About />} />


<Route path="/contact" element={<Contact />} />

</Routes>

</BrowserRouter>

);

export default App;

2⃣ Example Home.js

function Home() {

return <h2>Welcome to the Home Page!</h2>;

export default Home

You do the same for About.js and Contact.js — each returns its own content.

✅ How this works:

 BrowserRouter watches the URL.

 Routes contains all possible routes.

 Route matches the URL path to a component.

 Link lets you navigate without page reloads.

✅ Nested Routes

React Router also supports nested routes, so you can build pages inside pages — like a Dashboard with
sub-pages for Profile, Settings, etc.

✅ Advantages of Using Routing

✔ Lets you build multi-page apps inside a single-page setup.


✔ Pages load instantly — no waiting for the server to reload.
✔ Keeps the app organized by breaking it into smaller, clear components.
✔ Lets you manage complex navigation easily.

✅ Real-World Example
Apps like Facebook, Instagram, and Gmail are all single-page apps that use routing to switch between
pages without full reloads.

✅ Important Tips

✔ Always wrap your app in <BrowserRouter>.


✔ Use <Link> instead of <a href> — so the page does not reload.
✔ Organize routes clearly so your app is easy to navigate.
✔ For dynamic pages (like /user/:id), use route parameters.

✅ Key Points

 Routing makes React apps feel like real websites with multiple pages.

 React Router is the most popular tool for adding routing.

 Navigation is smooth and fast because there is no full reload.

 You can use nested routes and dynamic routes for bigger apps.

✅ Conclusion

Routing in React helps you build apps with multiple pages, clean URLs, and smooth navigation — all
inside a single-page application.
This makes your app look and feel professional, keeps users happy, and is a must-know skill for every
React developer.

You might also like