0% found this document useful (0 votes)
14 views

UNIT-V-REACT.JS

React.js is a widely used JavaScript library developed by Facebook for building user interfaces, particularly for single-page applications. It features a component-based architecture, a Virtual DOM for improved performance, and a declarative syntax that simplifies UI management. React's ecosystem supports cross-platform development and has a large community, making it a powerful choice for modern web applications.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

UNIT-V-REACT.JS

React.js is a widely used JavaScript library developed by Facebook for building user interfaces, particularly for single-page applications. It features a component-based architecture, a Virtual DOM for improved performance, and a declarative syntax that simplifies UI management. React's ecosystem supports cross-platform development and has a large community, making it a powerful choice for modern web applications.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 55

UNIT-V

REACT
NEED OF REACT
React.js, or simply React, is a popular JavaScript library for building user interfaces, especially for
single-page applications (SPAs). It was developed by Facebook and has grown to become one of
the most widely used front-end libraries in web development. React allows developers to build
fast, interactive, and dynamic UIs efficiently.
Key Features of React.js:
1. Component-Based Architecture:
o React promotes the use of components, which are reusable, self-contained units
of code that define how a part of the UI should appear.
o Components can be nested inside each other, leading to clean and modular code
that’s easy to manage.
2. Virtual DOM:
o React uses a Virtual DOM to improve performance. The Virtual DOM is a
lightweight copy of the actual DOM in memory.
o When state changes, React updates the Virtual DOM first, then compares it to
the actual DOM (a process called reconciliation) and only updates the parts of
the DOM that need to be changed. This results in faster updates and better
performance, especially for complex applications.
3. Declarative Syntax:
o React uses declarative syntax, which means you describe what you want the UI to
look like for a given state. React handles how to update the UI based on state
changes.
o For example, instead of manually manipulating the DOM, you write React
components that specify how the UI should update when data changes.
4. JSX (JavaScript XML):
o React uses JSX, which allows you to write HTML-like code within JavaScript.
o JSX makes it easier to describe what the UI should look like by blending HTML
structure with JavaScript logic in a single file, making code more readable and
concise.
5. One-Way Data Binding:
o React enforces one-way data flow, meaning data flows in a single direction,
typically from parent components to child components via props.
o This makes it easier to understand how data changes affect the UI and simplifies
debugging.
6. State Management:

1
o React components have state, which allows them to store and manage data that
changes over time.
o When the state of a component changes, React automatically re-renders the
component, ensuring the UI is always in sync with the underlying data.
7. React Hooks:
o React introduced Hooks in version 16.8, which allow you to use state and other
React features without writing class components.
o Common hooks include useState, useEffect, useContext, and more. Hooks make
React components simpler and easier to manage, especially for developers who
prefer functional components over class-based ones.
8. Routing:
o While React doesn’t provide built-in routing, libraries like React Router can be
used to add routing capabilities to a React app.
o React Router helps you define navigation between different pages or views in a
single-page application.
9. Ecosystem & Community:
o React has a rich ecosystem with many tools, libraries, and frameworks built
around it, such as Redux for state management, Next.js for server-side rendering,
and React Native for mobile app development.
o There’s also a large, active community providing support, tutorials, and open-
source projects.
10. Cross-Platform Development:
 React Native, a framework built on top of React, allows developers to build mobile
applications for iOS and Android using the same React concepts, leading to code
reusability across platforms.
How React.js Works:
 Components: React applications are made up of components, which can be thought of
as building blocks of the app. A component may represent a part of the UI, such as a
button or a list.
 Props and State: Components receive data via props (short for properties) from their
parent component. They also manage their own data internally via state.
 Rendering: React components render the UI based on their state and props. When the
state or props change, React re-renders the component to reflect the changes.
Benefits of Using React.js:
1. Performance: The Virtual DOM improves performance by reducing the number of
updates to the actual DOM, which is often a performance bottleneck in web
applications.

2
2. Flexibility: React’s ecosystem allows for great flexibility in how you structure and build
your app, giving you the freedom to choose libraries for routing, state management, etc.
3. Reusable Components: The component-based structure makes it easy to reuse code and
build scalable applications, reducing redundancy and improving maintainability.
4. Large Community & Ecosystem: React is well-supported with a huge community, tons of
tutorials, and third-party libraries that extend its functionality.
5. Cross-Platform: React Native allows developers to build mobile applications for iOS and
Android with React, so you can use the same codebase for both web and mobile apps.
Conclusion:
React.js is a powerful, efficient, and flexible library for building modern web applications. Its
component-based structure, virtual DOM, and robust ecosystem make it an excellent choice for
creating dynamic and interactive user interfaces. Whether you’re building a small project or a
large-scale application, React provides the tools needed to build fast, maintainable, and scalable
UIs.
SIMPLE REACT STRUCTURE
A simple React.js project structure is designed to organize the files and folders in a way that
makes the app easy to scale, maintain, and understand. Below is an example of a basic structure
for a React application:
Example of a Simple React.js Project Structure:
my-react-app/
├── node_modules/ # Dependencies installed by npm/yarn
├── public/ # Static assets that are served to the user (HTML, images, etc.)
│ ├── index.html # The main HTML file where the React app is injected
│ └── favicon.ico # Favicon of the app
├── src/ # Source code for the app
│ ├── assets/ # Folder for images, styles, fonts, etc.
│ │ └── logo.png # Example image file
│ ├── components/ # Reusable React components
│ │ ├── Header.js # Header component
│ │ └── Footer.js # Footer component
│ ├── App.js # Main component that acts as the entry point to the app
│ ├── index.js # Entry point for React app (rendering to the DOM)
│ ├── styles/ # CSS or SCSS files
│ │ └── App.css # CSS styles for the app
│ └── utils/ # Helper functions or utility files (optional)
│ └── formatDate.js # Example utility function
├── .gitignore # Files to be ignored by Git
├── package.json # Project metadata, dependencies, and scripts

3
├── README.md # Project documentation
└── package-lock.json # Locks the exact versions of dependencies
Explanation of Each Part:
1. node_modules/:
o This directory contains all of the dependencies installed by npm or yarn (React,
ReactDOM, and other third-party libraries).
2. public/:
o index.html: This is the single HTML file in a React application, where the React
components will be rendered. It typically contains a <div id="root"></div> tag,
which is where React injects the app.
o favicon.ico: The small icon that appears in the browser tab.
3. src/:
o index.js: The entry point of the React app. It renders the root component (usually
<App />) inside the div#root in the HTML file using ReactDOM.render().
o App.js: The root component of your application. This is where you can define the
layout and structure of your main UI.
o components/: Contains all the reusable components, such as headers, footers,
and buttons. In the example above, Header.js and Footer.js are placed here.
o styles/: This folder contains your CSS or SCSS files. App.css holds the styles for the
App.js component.
o assets/: Stores images, fonts, or other static files like logos.
o utils/: Optional. You can store helper functions here. For example, a utility
function to format dates can be placed in this folder.
4. package.json:
o Contains metadata about the project, such as the name, version, dependencies,
and scripts (e.g., npm start for running the app).
5. README.md:
o A markdown file to provide information about the project, how to set it up, and
any other necessary documentation.
6. .gitignore:
o Specifies which files or directories Git should ignore (such as node_modules/ or
build files).
Example Code for Basic Setup:
src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './styles/App.css'; // Importing global styles
import App from './App'; // Importing main App component

4
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
src/App.js
import React from 'react';
import Header from './components/Header';
import Footer from './components/Footer';

function App() {
return (
<div className="App">
<Header />
<main>
<h1>Welcome to My React App!</h1>
<p>This is a simple example.</p>
</main>
<Footer />
</div>
);
}

export default App;


src/components/Header.js
import React from 'react';

function Header() {
return (
<header>
<h1>My React Application</h1>
</header>
);
}

export default Header;

5
src/components/Footer.js
import React from 'react';

function Footer() {
return (
<footer>
<p>© 2025 My React App</p>
</footer>
);
}

export default Footer;


src/styles/App.css
.App {
text-align: center;
}

header {
background-color: #282c34;
color: white;
padding: 20px;
}

footer {
background-color: #282c34;
color: white;
padding: 10px;
position: fixed;
bottom: 0;
width: 100%;
}
Conclusion:
This is a simple React app structure with just a few components to get you started. As your app
grows, you can expand the folder structure, introduce state management libraries like Redux,
and organize your code further into subfolders or modules. The structure can be adapted based
on the scale of your project, but this gives a clear starting point for a React application.

THE VIRTUAL DOM

6
The Virtual DOM is one of the key concepts that makes React efficient and fast. It is an
abstraction of the actual DOM (Document Object Model), which is used to represent the
structure of an HTML document. Here's an in-depth explanation of what the Virtual DOM is and
how it works:
What is the Virtual DOM?
The Virtual DOM (VDOM) is a lightweight in-memory representation of the actual DOM. React
creates a virtual representation of the DOM elements in the form of JavaScript objects. This
allows React to keep track of what changes need to be made in the real DOM, without directly
manipulating it every time there’s a change.
Why Use the Virtual DOM?
In traditional web development (without React), when you change the data or state of an
application, you need to manually update the real DOM, which can be slow and inefficient,
especially when dealing with large, complex UIs. Direct manipulation of the DOM can result in
performance bottlenecks because the browser needs to re-render and repaint the entire UI
after every change.
React solves this problem by using the Virtual DOM to optimize the process of updating the real
DOM.
How Does the Virtual DOM Work?
Here’s a step-by-step breakdown of how React uses the Virtual DOM to efficiently update the
UI:
1. Initial Rendering:
o When the React app is first loaded, React creates a Virtual DOM tree that
represents the initial state of the UI.
o This Virtual DOM tree is a lightweight copy of the actual DOM and is stored in
memory.
2. State or Data Change:
o When there is a change in the state or props (i.e., the data that the component
depends on), React does not directly change the real DOM right away. Instead,
React updates the Virtual DOM first.
3. Reconciliation (Diffing):
o After the Virtual DOM is updated, React compares the new version of the Virtual
DOM with the previous version (this process is called reconciliation).
o React uses an efficient algorithm (the diffing algorithm) to compare the new
Virtual DOM tree with the previous one and identifies which parts of the UI have
changed.
4. Minimal DOM Updates:

7
o Once React knows which parts of the Virtual DOM have changed, it calculates the
minimal number of updates required and updates only those parts of the real
DOM.
o This selective update mechanism drastically reduces unnecessary re-renders and
enhances the app's performance.
5. Rendering the Real DOM:
o Finally, the changes are reflected in the real DOM, and the user sees the updated
UI without needing to refresh the entire page.
Key Benefits of the Virtual DOM:
1. Improved Performance:
o Direct manipulation of the real DOM can be slow, especially with large
applications. The Virtual DOM ensures that only the necessary parts of the UI are
re-rendered, reducing the overall number of updates to the real DOM.
o This minimizes the cost of expensive operations like layout calculations,
repainting, and reflowing the page.
2. Efficiency in Updating the UI:
o React doesn’t need to worry about updating the entire UI when state or data
changes. Instead, it updates the components that actually need to change, based
on the diffing algorithm.
o This makes React particularly effective when building complex, dynamic UIs that
update frequently (e.g., dashboards, social media feeds).
3. Simplified UI Management:
o React’s declarative syntax allows developers to focus on describing what the UI
should look like at any given time, instead of manually handling how and when to
update the UI. The Virtual DOM handles the optimization internally, so
developers don’t need to worry about inefficient DOM updates.
4. Cross-Browser Compatibility:
o React abstracts away the differences in how browsers handle DOM updates.
Since React handles updates in memory and then applies them to the DOM,
developers don’t have to worry about quirks in different browsers’ rendering
engines.
Virtual DOM vs Real DOM: A Comparison
Aspect Real DOM Virtual DOM
Every change triggers a full re-render of Only the parts that have changed are re-
Rendering
the entire DOM. rendered.
Manipulating the real DOM can be Faster, as updates are batched and only
Performance
slow, especially with large updates. minimal changes are applied.
Efficiency Less efficient, as unnecessary updates More efficient, as React performs diffing

8
Aspect Real DOM Virtual DOM
can occur. and only updates necessary parts.
React manages updates to the Virtual
Manipulation Direct manipulation of the real DOM.
DOM and applies them to the real DOM.
Example of the Virtual DOM in Action:
Imagine we have a simple React component that displays a counter value:
class Counter extends React.Component {
constructor() {
super();
this.state = { count: 0 };
}

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

render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={this.increment}>Increment</button>
</div>
);
}
}
When the user clicks the Increment button:
1. React updates the state (this.setState()).
2. The Virtual DOM is updated to reflect the new count value.
3. React compares the new Virtual DOM with the old one and identifies that only the p
element has changed.
4. React then updates the real DOM with just the new count, without needing to re-render
the entire page.
Conclusion:
The Virtual DOM is a key feature that allows React to optimize the process of updating the UI.
By creating a lightweight in-memory copy of the real DOM, React can efficiently calculate the
differences between the previous and current states, and only update the real DOM where
necessary. This makes React highly performant, especially for dynamic, interactive applications.

9
REACT COMPONENTS
INTRODUCING REACT COMPONENTS
In React, components are the building blocks of the user interface. They define the structure,
behavior, and appearance of parts of the UI, and they can be reused across different parts of the
application. Components make it easy to break down complex UIs into smaller, manageable
parts.
There are two types of React components:
1. Class Components (older approach)
2. Functional Components (modern approach, recommended)
Let’s go over both of them in detail:

1. Functional Components (Recommended Approach)


Functional components are simply JavaScript functions that return JSX (HTML-like syntax). Since
React 16.8, with the introduction of Hooks, functional components have become the preferred
way to build components, as they allow you to manage state and lifecycle methods just like
class components.
Example of a Functional Component:
import React, { useState } from 'react';

function Counter() {
const [count, setCount] = useState(0); // State hook to manage the count value

const increment = () => {


setCount(count + 1); // Update the count value when button is clicked
};

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

export default Counter;


Key Features of Functional Components:
 Simpler syntax: They're just functions that return JSX.

10
 Hooks: With the addition of hooks like useState, useEffect, etc., functional components
can now manage state, side effects, and lifecycle methods.
 Stateless or Stateful: Functional components can be stateless or use hooks to manage
state.
 Recommended for New Code: With the ease of hooks, functional components are
generally the preferred choice for writing React components in modern applications.

2. Class Components (Older Approach)


Class components were the original way of creating components in React. They are JavaScript
classes that extend React.Component and must define a render() method that returns JSX.
Example of a Class Component:
import React, { Component } from 'react';

class Counter extends Component {


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

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

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

export default Counter;


Key Features of Class Components:

11
 State and Lifecycle: Class components can have state and lifecycle methods (e.g.,
componentDidMount, componentWillUnmount).
 More Verbose: They tend to be more complex and verbose compared to functional
components, especially with lifecycle methods.
 Less Preferred Today: Due to the introduction of hooks, functional components have
become more popular and are recommended for new codebases.

JSX (JavaScript XML) in Components


React components use JSX to describe what the UI should look like. JSX is a syntax extension for
JavaScript, and it looks very similar to HTML, but it’s actually JavaScript.
For example, inside the return statement of a component:
return (
<div>
<h1>Hello, React!</h1>
<p>This is a functional component using JSX.</p>
</div>
);
Even though it looks like HTML, JSX is transformed into React.createElement() calls by the React
compiler.

Props (Properties) in React Components


Props are used to pass data from one component to another. A parent component can pass
props to a child component. The child component then uses these props to render UI.
Example of Passing Props:
Parent Component:
import React from 'react';
import Greeting from './Greeting'; // Importing the child component

function App() {
return (
<div>
<Greeting name="John" />
<Greeting name="Alice" />
</div>
);
}

export default App;

12
Child Component (Greeting.js):
import React from 'react';

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

export default Greeting;


Here, the Greeting component receives the name prop and uses it to render the greeting
message.

State in React Components


State is used to store data that can change over time in a component. It allows the component
to maintain its own data, which can be updated using functions like setState in class
components or the useState hook in functional components.
Example of State in a Functional Component:
import React, { useState } from 'react';

function Counter() {
const [count, setCount] = useState(0); // Declare state with the useState hook

const increment = () => {


setCount(count + 1); // Update state using the setter function
};

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

export default Counter;


In this example:
 The count variable holds the current state value.
 setCount is a function that updates the state.
Example of State in a Class Component:

13
import React, { Component } from 'react';

class Counter extends Component {


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

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

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

export default Counter;


Handling Events in React
React provides a way to handle events (like button clicks, form submissions, etc.). You can pass
event handler functions as props to elements. These handlers are written in camelCase.
Example of Event Handling:
import React, { useState } from 'react';

function ClickMe() {
const [message, setMessage] = useState('Click the button');

const handleClick = () => {


setMessage('Button Clicked!');
};

14
return (
<div>
<p>{message}</p>
<button onClick={handleClick}>Click Me</button>
</div>
);
}

export default ClickMe;


Here, the handleClick function is called when the button is clicked, and it updates the state to
display a different message.

Conclusion
 Components are the fundamental building blocks in React.
 There are two main types of components: Functional Components (preferred, especially
with hooks) and Class Components (older approach, still supported).
 JSX allows you to write HTML-like code within JavaScript.
 Props are used to pass data to components, and state is used to manage data that can
change over time.
 React components can handle events (like clicks) and update the UI accordingly.
By breaking down your application into smaller, reusable components, React makes it easier to
build and maintain complex UIs.

CREATING COMPONENTS IN REACT


In React, a component is a JavaScript function or class that optionally accepts inputs (called
props) and returns a React element that describes how a section of the UI should appear.
Creating components is the fundamental part of building a React application. Let’s dive into how
you can create functional components and class components, the two main types of
components in React.
1. Creating a Functional Component
A functional component is a simpler way to create components in React. It is just a JavaScript
function that returns JSX (JavaScript XML). Since the introduction of React Hooks, functional
components can manage state and side effects, making them the modern way to write
components.
Example of a Simple Functional Component:
// Welcome.js
import React from 'react';

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

export default Welcome;


In this example:
 Welcome is a functional component that simply renders a heading.
 It doesn't accept any props or have state in this case, but you can add them as needed.
Using the Functional Component:
To use this Welcome component in another component (e.g., an App component), you would
import and render it like this:
import React from 'react';
import ReactDOM from 'react-dom';
import Welcome from './Welcome';

function App() {
return (
<div>
<Welcome /> {/* Rendering the Welcome component */}
</div>
);
}

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


Here, App is the parent component, and it renders the Welcome component inside its JSX.

2. Creating a Functional Component with Props


Props (short for "properties") are used to pass data from a parent component to a child
component. In functional components, props are passed as arguments to the function.
Example of a Functional Component with Props:
// Greeting.js
import React from 'react';

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

export default Greeting;

16
Here:
 Greeting is a functional component that takes props as an argument.
 props.name is used to display the name passed to the Greeting component.
Using the Functional Component with Props:
Now, to pass the name prop from the parent component to Greeting:
import React from 'react';
import ReactDOM from 'react-dom';
import Greeting from './Greeting';

function App() {
return (
<div>
<Greeting name="Alice" />
<Greeting name="Bob" />
</div>
);
}

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


In this case, the parent App passes a name prop to the Greeting component, which is rendered
as part of the UI.

3. Creating a Class Component


Class components are a more traditional way of creating React components. They are ES6
classes that extend React.Component. Class components can manage state and handle lifecycle
methods.
Example of a Simple Class Component:
import React, { Component } from 'react';

class Welcome extends Component {


render() {
return <h1>Hello, Welcome to React!</h1>;
}
}

export default Welcome;


Here:
 Welcome is a class component.

17
 It uses the render method to return JSX, just like functional components.
Using the Class Component:
You can use the Welcome class component in a parent component:
import React from 'react';
import ReactDOM from 'react-dom';
import Welcome from './Welcome';

class App extends React.Component {


render() {
return (
<div>
<Welcome /> {/* Rendering the class component */}
</div>
);
}
}

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


4. Creating a Class Component with Props
Just like in functional components, you can pass props to class components. In class
components, props are accessed using this.props.
Example of a Class Component with Props:
import React, { Component } from 'react';

class Greeting extends Component {


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

export default Greeting;


Here:
 Greeting is a class component.
 this.props.name is used to access the name prop passed from the parent.
Using the Class Component with Props:
import React from 'react';
import ReactDOM from 'react-dom';
import Greeting from './Greeting';

18
class App extends React.Component {
render() {
return (
<div>
<Greeting name="Alice" />
<Greeting name="Bob" />
</div>
);
}
}

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


5. Adding State to a Class Component
Class components can have their own internal state, which allows them to track data that
changes over time. State is initialized in the constructor, and changes to state are done using
this.setState().
Example of a Class Component with State:
import React, { Component } from 'react';

class Counter extends Component {


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

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

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

19
);
}
}

export default Counter;


Here:
 The Counter component has a count state initialized to 0.
 The increment method updates the state when the button is clicked.
Using the Class Component with State:
import React from 'react';
import ReactDOM from 'react-dom';
import Counter from './Counter';

class App extends React.Component {


render() {
return (
<div>
<Counter /> {/* Rendering the stateful class component */}
</div>
);
}
}

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

6. Creating a Functional Component with State (using Hooks)


With the introduction of Hooks in React 16.8, functional components can now manage their
own state. The useState hook is used for this purpose.
Example of a Functional Component with State:
import React, { useState } from 'react';

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

const increment = () => {


setCount(count + 1);
};

20
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
</div>
);
}

export default Counter;


Here:
 The useState hook is used to create state (count) and a function to update it (setCount).
 The increment function updates the state when the button is clicked.
Using the Functional Component with State:
import React from 'react';
import ReactDOM from 'react-dom';
import Counter from './Counter';

function App() {
return (
<div>
<Counter /> {/* Rendering the stateful functional component */}
</div>
);
}

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

7. Conclusion: Creating React Components


 Functional Components are the modern and preferred way to create components,
especially with the power of hooks for managing state and side effects.
 Class Components are still valid, but they tend to be more verbose and less flexible
compared to functional components with hooks.
 Props are used to pass data down from parent to child components.
 State is used to manage data that can change over time, and both class components and
functional components can use state (class components use this.setState(), and
functional components use useState()).
React components let you break down your application into smaller, reusable pieces, making
development more manageable, scalable, and easier to maintain.

21
DATA AND DATA FLOW IN REACT
In React, data refers to the values that are passed between components and used to determine
the appearance and behavior of the UI. Understanding how data flows within a React
application is crucial for building efficient and maintainable applications. React follows a
unidirectional data flow, meaning that data moves in one direction, typically from a parent
component to its child components.
Let's dive deeper into how data works in React, including the concepts of props, state, and the
flow of data within a React app.

1. Props: Passing Data from Parent to Child


Props (short for "properties") are used to pass data from a parent component to a child
component in React. Props are read-only, meaning that child components cannot modify them
directly.
How Props Work:
 Data is passed from a parent component to a child component via props.
 Props are immutable, meaning a child cannot change the props it receives from a parent.
 Props are used to customize or configure child components.
Example of Props:
// Parent Component
import React from 'react';
import Greeting from './Greeting';

function App() {
return (
<div>
<Greeting name="Alice" />
<Greeting name="Bob" />
</div>
);
}

export default App;


// Child Component (Greeting)
import React from 'react';

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

22
}

export default Greeting;


 In this example, the App component passes a name prop to each Greeting component.
The Greeting component uses that prop to display a personalized message.
 The name prop is read-only and cannot be changed by the Greeting component.

2. State: Managing Data within a Component


State is used to store data that can change over time within a component. Unlike props, state is
mutable—meaning a component can modify its own state. State is often used to handle user
interactions, form inputs, or any dynamic data.
How State Works:
 State is local to the component and is initialized using the useState hook (for functional
components) or in the constructor (for class components).
 When state changes, the component re-renders to reflect the updated data in the UI.
Example of State in a Functional Component:
import React, { useState } from 'react';

function Counter() {
const [count, setCount] = useState(0); // useState hook for state management

const increment = () => {


setCount(count + 1); // Updating state using the setter function
};

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

export default Counter;


 The Counter component uses the useState hook to initialize the count state to 0.
 When the user clicks the "Increment" button, the count state is updated, which causes
the component to re-render with the updated count.
Example of State in a Class Component:

23
import React, { Component } from 'react';

class Counter extends Component {


constructor(props) {
super(props);
this.state = { count: 0 }; // Initializing state in the constructor
}

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

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

export default Counter;


 Here, the Counter class component initializes the count state in the constructor.
 The increment method updates the state using this.setState, triggering a re-render of
the component.

3. Data Flow in React


React uses unidirectional data flow, meaning that data flows in a single direction, typically from
the top-level parent component down to the child components.
Parent-to-Child Data Flow (Props):
 Parent components can pass data to child components through props.
 A child component can access these props, but it cannot modify them directly. If a child
component needs to change some data, it must notify the parent to update the data and
re-pass it down as props.
Example of Data Flow (Props):
// Parent Component (App)
import React, { useState } from 'react';

24
import Greeting from './Greeting';

function App() {
const [name, setName] = useState("Alice");

const changeName = () => {


setName("Bob");
};

return (
<div>
<Greeting name={name} />
<button onClick={changeName}>Change Name</button>
</div>
);
}

export default App;


// Child Component (Greeting)
import React from 'react';

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

export default Greeting;


 In this case, the App component passes the name state to the Greeting child component
as a prop.
 When the button is clicked, the changeName function is called, updating the state in App
(changing the name from "Alice" to "Bob").
 The updated name prop is passed down to Greeting, and the UI re-renders with the new
name.
Child-to-Parent Data Flow (Event Handling):
While a child component cannot directly modify the state of its parent, it can trigger a change in
the parent through an event handler function passed down via props.
// Parent Component (App)
import React, { useState } from 'react';
import Button from './Button';

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

const incrementCount = () => {


setCount(count + 1);
};

return (
<div>
<p>Count: {count}</p>
<Button onClick={incrementCount} />
</div>
);
}

export default App;


// Child Component (Button)
import React from 'react';

function Button(props) {
return <button onClick={props.onClick}>Increment</button>;
}

export default Button;


 The Button component is a child component that receives an onClick prop from the
parent (App).
 When the button is clicked, the onClick function is triggered, which calls incrementCount
in the parent (App) and updates the count state.
 This triggers a re-render of App, updating the displayed count.

4. State Lifting: Sharing Data Between Sibling Components


Sometimes, two sibling components need to share data. Since props flow from parent to child,
you can lift the state up to the parent and pass the data down to both sibling components as
props.
Example of Lifting State Up:
// Parent Component (App)
import React, { useState } from 'react';

26
import Input from './Input';
import Display from './Display';

function App() {
const [text, setText] = useState("");

const handleTextChange = (newText) => {


setText(newText);
};

return (
<div>
<Input onTextChange={handleTextChange} />
<Display text={text} />
</div>
);
}

export default App;


// Child Component (Input)
import React from 'react';

function Input(props) {
const handleChange = (event) => {
props.onTextChange(event.target.value); // Passing data to parent
};

return <input type="text" onChange={handleChange} />;


}

export default Input;


// Child Component (Display)
import React from 'react';

function Display(props) {
return <p>You typed: {props.text}</p>;
}

27
export default Display;
 In this example, the App component holds the text state and passes it down to the
Display component as a prop.
 The Input component receives a function (onTextChange) as a prop, which it calls
whenever the input changes, passing the new text back to the parent (App).
 This is an example of lifting state up to share data between sibling components.

5. The Flow of Data Summary


 Parent-to-Child (Props): Data is passed from parent components to child components via
props. Child components receive data but cannot modify it directly.
 Child-to-Parent (Event Handlers): Child components can send data back to parents by
calling functions passed down as props.
 State: Each component can maintain its own local state, and changes in state cause the
component to re-render.
 State Lifting: If two sibling components need to share state, the state is lifted up to the
parent component, and the parent then passes it down as props.

Conclusion
React follows a unidirectional data flow, making it predictable and easy to understand. By using
props to pass data from parent to child and state to manage data within components, React
helps keep the UI consistent and responsive. Understanding how data flows within React
applications is key to building dynamic, interactive UIs.

RENDERING LIFE CYCLE METHODS IN REACT


In React, rendering refers to the process of determining what should be displayed on the
screen, and lifecycle methods are special methods that can be called at different points in a
component's life—from its creation to its removal. React components undergo a lifecycle during
their existence, and understanding how to use these lifecycle methods is crucial for building
efficient, dynamic React applications.
React components can be broadly divided into two types: Functional Components (using hooks)
and Class Components (using lifecycle methods).
1. Rendering in React
In React, rendering is the process of converting the React components into actual UI elements
that are displayed on the screen. React performs the rendering process by calling the render()
method (for class components) or returning JSX from the component function (for functional
components).
 Functional Components render automatically when the component’s state or props
change.

28
 Class Components use the render() method to return JSX.
Example of Rendering in Functional Components:
import React from 'react';

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

export default Greeting;


Here, the Greeting component renders the JSX output when it is called.
Example of Rendering in Class Components:
import React, { Component } from 'react';

class Greeting extends Component {


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

export default Greeting;


Here, the Greeting class component uses the render() method to return JSX.

2. Lifecycle Methods in Class Components


In class components, React provides special methods called lifecycle methods to run code at
specific points during the component's lifecycle. These methods allow you to manage the
component’s behavior during different stages of its life.
The lifecycle methods can be broken into three main phases:
 Mounting: When the component is being created and inserted into the DOM.
 Updating: When the component’s state or props change and the component is re-
rendered.
 Unmounting: When the component is being removed from the DOM.
A. Mounting Phase (Component Initialization)
The mounting phase occurs when a component is being created and inserted into the DOM.
There are three key lifecycle methods in this phase:
1. constructor(): The constructor is called when the component is initialized. It is used for
setting the initial state and binding event handlers.
2. constructor(props) {
3. super(props);

29
4. this.state = { count: 0 };
5. }
6. componentDidMount(): This method is called once the component is rendered to the
screen. It’s useful for fetching data or interacting with external APIs when the
component is first loaded.
7. componentDidMount() {
8. console.log("Component has mounted!");
9. }
B. Updating Phase (Component State or Props Change)
When a component’s state or props change, it triggers an update, and the following methods
are invoked:
1. static getDerivedStateFromProps(nextProps, nextState): This method is called right
before rendering. It allows the component to update its state based on changes to
props.
2. static getDerivedStateFromProps(nextProps, nextState) {
3. // Return the updated state based on props
4. return null;
5. }
6. shouldComponentUpdate(nextProps, nextState): This method is used to determine
whether the component should re-render. By default, it returns true. You can return
false to prevent unnecessary re-renders.
7. shouldComponentUpdate(nextProps, nextState) {
8. return nextState.count !== this.state.count;
9. }
10. render(): This method is called when the component needs to re-render. It is the only
required method in class components. React uses the render() method to return JSX.
11. render() {
12. return <div>{this.state.count}</div>;
13. }
14. componentDidUpdate(prevProps, prevState): This method is called after the component
has re-rendered. It’s useful for operations like updating the DOM or interacting with APIs
after state/prop changes.
15. componentDidUpdate(prevProps, prevState) {
16. console.log("Component updated!");
17. }
C. Unmounting Phase (Component Removal)
The unmounting phase occurs when a component is being removed from the DOM. The only
lifecycle method in this phase is:

30
1. componentWillUnmount(): This method is called right before the component is removed
from the DOM. It is useful for cleanup operations like canceling network requests or
clearing timers.
2. componentWillUnmount() {
3. console.log("Component will be removed");
4. }

3. Lifecycle Methods in a Class Component: Example


Here’s an example of how these lifecycle methods can be used together in a class component:
import React, { Component } from 'react';

class LifecycleExample extends Component {


constructor(props) {
super(props);
this.state = { count: 0 };
console.log("Constructor");
}

static getDerivedStateFromProps(nextProps, nextState) {


console.log("getDerivedStateFromProps");
return null; // No state update here
}

shouldComponentUpdate(nextProps, nextState) {
console.log("shouldComponentUpdate");
return true; // Allow re-rendering
}

render() {
console.log("render");
return (
<div>
<h1>{this.state.count}</h1>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>Increment</button>
</div>
);
}

31
componentDidMount() {
console.log("componentDidMount");
}

componentDidUpdate(prevProps, prevState) {
console.log("componentDidUpdate");
}

componentWillUnmount() {
console.log("componentWillUnmount");
}
}

export default LifecycleExample;


In this example:
 The constructor() initializes the component state.
 The getDerivedStateFromProps() is called before rendering (though it doesn’t change
any state here).
 The shouldComponentUpdate() method controls whether the component should re-
render.
 The render() method displays the count.
 The componentDidMount() method runs after the component mounts (good for data
fetching).
 The componentDidUpdate() method runs after every update (good for side effects after
rendering).
 The componentWillUnmount() method is called before the component unmounts (good
for cleanup).

4. Functional Components and Hooks: Lifecycle with useEffect


With the introduction of hooks in React, functional components now have the ability to manage
side effects and lifecycle behavior using the useEffect hook. The useEffect hook combines the
functionality of componentDidMount, componentDidUpdate, and componentWillUnmount into
a single API.
useEffect Hook Syntax
useEffect(() => {
// Code to run on mount and/or update

return () => {

32
// Cleanup code (optional), runs on unmount or before the effect is re-run
};
}, [dependencies]); // Optional dependency array to control when effect runs
Example of useEffect in a Functional Component:
import React, { useState, useEffect } from 'react';

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

// Equivalent to componentDidMount and componentDidUpdate


useEffect(() => {
console.log("Component has mounted or updated!");

// Cleanup function, equivalent to componentWillUnmount


return () => {
console.log("Cleanup on unmount or before re-run");
};
}, [count]); // The effect depends on the 'count' state

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

export default Counter;


In this example:
 The useEffect hook runs after the component mounts (like componentDidMount), and it
will run again when count changes (like componentDidUpdate).
 The cleanup function inside useEffect is run when the component unmounts or before
the effect is re-executed (like componentWillUnmount).

5. Key Takeaways
 Class Components use lifecycle methods (componentDidMount, componentDidUpdate,
componentWillUnmount, etc.) to manage different phases of the component lifecycle.

33
 Functional Components now use React Hooks (like useEffect) to replicate lifecycle
behavior, making functional components more powerful and preferred in modern React
development.
 Understanding lifecycle methods and how to manage side effects and state changes is
crucial for building efficient, interactive React applications.
React’s lifecycle management allows you to control the behavior of your components as they
are created, updated, and removed, enabling you to optimize performance and handle side
effects effectively.

WORKING WITH FORMS IN REACT


Working with Forms in React
Handling forms is a fundamental part of many web applications, and React makes it easy to
manage form inputs, validation, and submission. In React, form elements like <input>,
<textarea>, <select>, etc., can be controlled using state to manage their values. This gives you
complete control over user input, making it easy to validate, format, or submit the data.
In this guide, we’ll explore how to handle forms in React using both controlled and uncontrolled
components, as well as how to handle form submission.

1. Controlled Components
A controlled component is an input element whose value is controlled by React's state. In React,
the value of the form element is set by the state, and the state is updated whenever the user
interacts with the form.
How Controlled Components Work:
 The form element’s value is bound to the component’s state.
 Changes to the input field are handled by an event handler that updates the state.
 The component re-renders whenever the state changes, keeping the UI in sync with the
data.
Example of a Controlled Form Component:
import React, { useState } from 'react';

function Form() {
// Initialize state to store form input
const [name, setName] = useState('');
const [email, setEmail] = useState('');

// Handle input changes


const handleNameChange = (event) => {
setName(event.target.value); // Update state with input value

34
};

const handleEmailChange = (event) => {


setEmail(event.target.value); // Update state with email value
};

// Handle form submission


const handleSubmit = (event) => {
event.preventDefault(); // Prevent default form submission
console.log('Name:', name, 'Email:', email); // Output form data
};

return (
<form onSubmit={handleSubmit}>
<label>
Name:
<input
type="text"
value={name} // Controlled input
onChange={handleNameChange} // Handle change event
/>
</label>
<br />
<label>
Email:
<input
type="email"
value={email} // Controlled input
onChange={handleEmailChange} // Handle change event
/>
</label>
<br />
<button type="submit">Submit</button>
</form>
);
}

export default Form;

35
Key Points:
 value={name} and value={email}: The input fields' values are controlled by React's state.
 onChange handlers: As the user types, the onChange event handlers update the state.
 Form submission: The handleSubmit function processes the form when submitted.

2. Uncontrolled Components
In an uncontrolled component, the form data is handled by the DOM itself, rather than React
state. Instead of controlling the value of the form element via React state, you use a ref to
access the form element and its value directly.
Uncontrolled components are useful when you don't need to track every keystroke or manage
form values directly with React state. They offer a simpler approach in cases where React's state
management may not be necessary.
Example of an Uncontrolled Component:
import React, { useRef } from 'react';

function Form() {
// Create refs to access form elements
const nameRef = useRef();
const emailRef = useRef();

// Handle form submission


const handleSubmit = (event) => {
event.preventDefault();
console.log('Name:', nameRef.current.value); // Access value from ref
console.log('Email:', emailRef.current.value); // Access value from ref
};

return (
<form onSubmit={handleSubmit}>
<label>
Name:
<input
type="text"
ref={nameRef} // Ref to access the input element
/>
</label>
<br />
<label>

36
Email:
<input
type="email"
ref={emailRef} // Ref to access the input element
/>
</label>
<br />
<button type="submit">Submit</button>
</form>
);
}

export default Form;


Key Points:
 useRef(): React’s useRef hook creates references to form elements.
 The values of the inputs are not controlled by React state, but accessed directly through
the ref using .current.value.
 handleSubmit() accesses the input values using nameRef.current.value and
emailRef.current.value when the form is submitted.

3. Form Validation
Form validation is often required before submitting the data. With React, you can perform
validation by checking the input values inside the handleSubmit function or by using the
onChange event handler to validate the form in real-time.
Example of Form Validation in a Controlled Component:
import React, { useState } from 'react';

function Form() {
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const [errors, setErrors] = useState({});

const handleNameChange = (event) => {


setName(event.target.value);
};

const handleEmailChange = (event) => {


setEmail(event.target.value);

37
};

const validateForm = () => {


const newErrors = {};
if (!name) newErrors.name = 'Name is required';
if (!email) newErrors.email = 'Email is required';
else if (!/\S+@\S+\.\S+/.test(email)) newErrors.email = 'Email is invalid';
setErrors(newErrors);
return Object.keys(newErrors).length === 0;
};

const handleSubmit = (event) => {


event.preventDefault();
if (validateForm()) {
console.log('Form submitted:', { name, email });
}
};

return (
<form onSubmit={handleSubmit}>
<label>
Name:
<input type="text" value={name} onChange={handleNameChange} />
{errors.name && <p>{errors.name}</p>}
</label>
<br />
<label>
Email:
<input type="email" value={email} onChange={handleEmailChange} />
{errors.email && <p>{errors.email}</p>}
</label>
<br />
<button type="submit">Submit</button>
</form>
);
}

export default Form;

38
Key Points:
 Validation logic: The validateForm() function checks if the name and email are provided
and if the email is in a valid format.
 Displaying errors: If validation fails, error messages are shown below the respective
input fields.

4. Handling Multiple Inputs


Sometimes, a form may have many inputs. Managing each input with its own state can be
cumbersome, especially if there are many fields. Instead, you can store all input values in a
single object or use dynamic state handling.
Example of Handling Multiple Inputs in a Controlled Component:
import React, { useState } from 'react';

function Form() {
const [formData, setFormData] = useState({
name: '',
email: '',
password: ''
});

const handleInputChange = (event) => {


const { name, value } = event.target;
setFormData({
...formData,
[name]: value, // Dynamically update the specific input field
});
};

const handleSubmit = (event) => {


event.preventDefault();
console.log(formData); // Log all form data at once
};

return (
<form onSubmit={handleSubmit}>
<label>
Name:
<input

39
type="text"
name="name"
value={formData.name}
onChange={handleInputChange}
/>
</label>
<br />
<label>
Email:
<input
type="email"
name="email"
value={formData.email}
onChange={handleInputChange}
/>
</label>
<br />
<label>
Password:
<input
type="password"
name="password"
value={formData.password}
onChange={handleInputChange}
/>
</label>
<br />
<button type="submit">Submit</button>
</form>
);
}

export default Form;


Key Points:
 Dynamic handling of inputs: The handleInputChange function updates the value of any
input dynamically by using the name attribute to determine which field to update.
 Single state object: All form data is stored in a single object, making it easier to manage
multiple inputs.

40
5. Handling File Inputs
To handle file inputs, React provides the File object, which you can access through the input
element’s files property. You can use this property to access files selected by the user.
Example of Handling File Inputs:
import React, { useState } from 'react';

function FileUploadForm() {
const [file, setFile] = useState(null);

const handleFileChange = (event) => {


setFile(event.target.files[0]); // Get the first file from the input
};

const handleSubmit = (event) => {


event.preventDefault();
if (file) {
console.log('File selected:', file.name);
} else {
console.log('No file selected');
}
};

return (
<form onSubmit={handleSubmit}>
<label>
Choose a file:
<input type="file" onChange={handleFileChange} />
</label>
<br />
<button type="submit">Submit</button>
</form>
);
}

export default FileUploadForm;


Key Points:

41
 event.target.files: The files property contains a list of selected files. You can use files[0]
to get the first file.
 Handling file submission: When the form is submitted, the file information (name, size,
type, etc.) can be accessed and processed.

Conclusion
In React, working with forms involves two primary approaches:
 Controlled components: Where React manages the form element's state, giving you
more control over the form data.
 Uncontrolled components: Where the DOM manages the form state, and React interacts
with it through refs.
You can also easily handle form validation, multiple inputs, and file inputs within React forms.
By understanding these concepts, you can build robust forms in your React applications that
offer a smooth and interactive user experience.

INTEGRATING THIRD PARTY LIBRARIES


Integrating Third-Party Libraries in React
One of the key strengths of React is its flexibility and the ability to integrate with many third-
party libraries that can help you implement functionality like UI components, animations, form
handling, HTTP requests, routing, and more. React makes it relatively easy to integrate third-
party libraries, whether they are written specifically for React or are standard JavaScript
libraries.
Here’s a guide on how to integrate third-party libraries in a React project:

1. Installing Third-Party Libraries


You can install third-party libraries using npm (Node Package Manager) or yarn. Both are
package managers that allow you to install and manage dependencies in your project.
Example: Installing a Library with npm
npm install <library-name>
For example, if you want to install the popular Axios library for making HTTP requests:
npm install axios
You can also install libraries globally (though it’s generally recommended to install them locally
for React projects).
Example: Installing a Library with Yarn
yarn add <library-name>
2. Using Third-Party Libraries in React
After installing a third-party library, you can import it into your React components and use its
features.

42
Example 1: Using Axios for HTTP Requests
Let's say you want to use Axios to make HTTP requests. Here's how you would integrate it into a
React component.
1. Install Axios (if you haven’t already):
npm install axios
2. Use Axios in your React component:
import React, { useState, useEffect } from 'react';
import axios from 'axios';

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

useEffect(() => {
// Fetch data from an API when the component mounts
axios.get('https://jsonplaceholder.typicode.com/posts')
.then((response) => {
setData(response.data);
})
.catch((error) => {
console.error("There was an error fetching the data!", error);
});
}, []); // Empty dependency array to run only once after initial render

return (
<div>
<h1>Fetched Data:</h1>
<ul>
{data.map(item => (
<li key={item.id}>{item.title}</li>
))}
</ul>
</div>
);
}

export default App;


3. Using Non-React Specific Libraries (e.g., jQuery, Chart.js)

43
Sometimes, you may need to use libraries that aren't specifically designed for React. Libraries
like jQuery, Chart.js, or D3.js can still be used with React, though you may need to handle the
integration carefully.
Example: Using Chart.js for Data Visualization
1. Install Chart.js:
npm install chart.js
2. Import and use Chart.js inside a React component:
import React, { useEffect, useRef } from 'react';
import { Chart } from 'chart.js';

function ChartComponent() {
const chartRef = useRef();

useEffect(() => {
const ctx = chartRef.current.getContext('2d');
new Chart(ctx, {
type: 'bar',
data: {
labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: ['rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86,
0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)'],
borderColor: ['rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)'],
borderWidth: 1
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
}
}
});

44
// Cleanup chart on unmount
return () => {
chartRef.current = null; // Dispose of chart
};
}, []);

return (
<div>
<canvas ref={chartRef}></canvas>
</div>
);
}

export default ChartComponent;


In this example:
 We use a ref to access the <canvas> element.
 The Chart.js library is instantiated inside the useEffect hook and renders the chart when
the component mounts.
 We also clean up the chart when the component unmounts to avoid memory leaks.

4. Using React-Specific Third-Party Libraries


There are many libraries specifically built for React that provide easy-to-use components for
things like forms, modals, routing, animations, and more.
Example 1: Using React Router for Navigation
1. Install React Router:
npm install react-router-dom
2. Set up routing in your React app:
import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';

function Home() {
return <h1>Home Page</h1>;
}

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

45
function App() {
return (
<Router>
<Switch>
<Route path="/" exact component={Home} />
<Route path="/about" component={About} />
</Switch>
</Router>
);
}

export default App;


 The react-router-dom library is used for handling client-side routing. You can switch
between different pages (or views) based on the URL.
 BrowserRouter manages the history and location of the app, while Route components
define the mapping of URL paths to components.
Example 2: Using React-Bootstrap for UI Components
1. Install React-Bootstrap:
npm install react-bootstrap bootstrap
2. Use React-Bootstrap components:
import React from 'react';
import { Button, Alert } from 'react-bootstrap';
import 'bootstrap/dist/css/bootstrap.min.css';

function App() {
return (
<div className="App">
<Alert variant="success">This is a success alert!</Alert>
<Button variant="primary">Click Me</Button>
</div>
);
}

export default App;


 React-Bootstrap provides React components wrapped around Bootstrap’s CSS
framework.
 The Button and Alert components are pre-styled and ready to use.

46
5. Handling External JavaScript Libraries
In some cases, a third-party library may not have a React version or be React-specific, and you
may need to integrate it by adding external scripts to your project.
1. You can add external libraries using script tags in public/index.html:
<!-- Add external library in public/index.html -->
<script src="https://cdn.jsdelivr.net/npm/some-third-party-library@version"></script>
2. Access the library from the global window object:
import React, { useEffect } from 'react';

function ExternalLibraryComponent() {
useEffect(() => {
// Access the third-party library once it is available
if (window.SomeLibrary) {
window.SomeLibrary.initialize();
}
}, []);

return <div>Using an external library in React!</div>;


}

export default ExternalLibraryComponent;


This method is commonly used when integrating non-React libraries like jQuery plugins, non-
React charting libraries, or external services that don’t have React bindings.

6. Conclusion
Integrating third-party libraries into a React project is straightforward, whether they are React-
specific or generic JavaScript libraries. The general process involves:
 Installing the library via npm or yarn.
 Importing the library into your component or app.
 Using the library’s features in your app, making sure to properly manage lifecycle events,
especially if the library interacts with the DOM.
 If needed, managing external scripts and handling cleanup appropriately to avoid
memory leaks.
Using third-party libraries is a great way to enhance your app’s functionality and leverage pre-
built solutions to save development time.

ROUTING IN REACT
Routing in React

47
In React, routing allows you to navigate between different components (or "pages") in your
application without reloading the browser page. This is especially useful for Single Page
Applications (SPAs), where you want the app to behave like a traditional website, with different
views or pages, but without the full page reloads.
React uses a popular routing library called React Router to handle this functionality. React
Router allows you to define routes for different components and map them to URL paths.
Here's how you can set up and use routing in React using React Router.

1. Installing React Router


To use React Router, you need to install the react-router-dom package:
npm install react-router-dom
For a React Native project, you would install react-router-native instead.

2. Basic Concepts of React Router


React Router provides several key components that are used to enable routing:
 BrowserRouter: This component is responsible for managing the history and location of
the app. It uses the HTML5 history API to keep the UI in sync with the URL.
 Route: This component is used to define which component should be rendered based on
the URL.
 Switch: This component renders the first Route that matches the current URL. It helps
avoid rendering multiple components for different routes when only one route should
be rendered.
 Link: This component is used for navigation within the app. It’s like an anchor tag (<a>) in
HTML but without causing a full-page reload.

3. Setting Up Basic Routing


Let’s set up basic routing with React Router by creating multiple pages (components) and
navigating between them.
Example:
1. Create your components/pages:
// Home.js
import React from 'react';

function Home() {
return <h1>Home Page</h1>;
}

export default Home;

48
// About.js
import React from 'react';

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

export default About;

// Contact.js
import React from 'react';

function Contact() {
return <h1>Contact Page</h1>;
}

export default Contact;


2. Set up routing in App.js:
import React from 'react';
import { BrowserRouter as Router, Route, Switch, Link } from 'react-router-dom';
import Home from './Home';
import About from './About';
import Contact from './Contact';

function App() {
return (
<Router>
<div>
<nav>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
<li>

49
<Link to="/contact">Contact</Link>
</li>
</ul>
</nav>

{/* Switch to render only one route */}


<Switch>
<Route path="/" exact component={Home} />
<Route path="/about" component={About} />
<Route path="/contact" component={Contact} />
</Switch>
</div>
</Router>
);
}

export default App;


Explanation:
 BrowserRouter: We wrap the app in a <Router> component to enable routing
functionality.
 Link: Used to navigate between routes. to attribute specifies the path.
 Route: Specifies which component should be rendered when a specific path is matched.
path is the URL pattern and component is the React component to display for that URL.
 Switch: Ensures that only one route is rendered at a time, by rendering the first
matching route.

4. Dynamic Routing with Route Parameters


React Router allows you to handle dynamic URLs with parameters. For example, you may want
to display different content based on the ID of a resource in the URL, like example.com/user/1.
Example: Dynamic Route with Parameters
1. Create a User component:
// User.js
import React from 'react';
import { useParams } from 'react-router-dom';

function User() {
// Accessing the dynamic parameter (userId)
const { userId } = useParams();

50
return <h1>User ID: {userId}</h1>;
}

export default User;


2. Add the dynamic route in App.js:
import React from 'react';
import { BrowserRouter as Router, Route, Switch, Link } from 'react-router-dom';
import User from './User';

function App() {
return (
<Router>
<div>
<nav>
<ul>
<li>
<Link to="/user/1">User 1</Link>
</li>
<li>
<Link to="/user/2">User 2</Link>
</li>
</ul>
</nav>

<Switch>
{/* Dynamic route */}
<Route path="/user/:userId" component={User} />
</Switch>
</div>
</Router>
);
}

export default App;


Key Points:
 useParams(): This hook is used to access the route parameters (in this case, userId).

51
 /user/:userId: The colon (:) syntax defines a parameter in the URL. React Router will
treat this as a dynamic route.

5. Redirecting to Another Route


You may want to programmatically redirect a user to another route. React Router provides the
Redirect component to handle this.
Example: Redirect after form submission
import React, { useState } from 'react';
import { Redirect } from 'react-router-dom';

function SubmitForm() {
const [submitted, setSubmitted] = useState(false);

const handleSubmit = () => {


// Simulate form submission
setSubmitted(true);
};

if (submitted) {
// Redirect to a success page
return <Redirect to="/success" />;
}

return (
<div>
<button onClick={handleSubmit}>Submit</button>
</div>
);
}

export default SubmitForm;


Key Points:
 Redirect: When submitted is true, the user is redirected to the /success page.
 Programmatic Redirect: You can also use history.push() or history.replace() for more
control.

6. Nested Routes

52
React Router also allows you to define nested routes, which are useful when you need to
structure your routes hierarchically.
Example: Nested Routes
import React from 'react';
import { BrowserRouter as Router, Route, Switch, Link } from 'react-router-dom';

function Dashboard() {
return (
<div>
<h1>Dashboard</h1>
<nav>
<ul>
<li>
<Link to="/dashboard/overview">Overview</Link>
</li>
<li>
<Link to="/dashboard/stats">Stats</Link>
</li>
</ul>
</nav>
<Switch>
<Route path="/dashboard/overview" component={Overview} />
<Route path="/dashboard/stats" component={Stats} />
</Switch>
</div>
);
}

function Overview() {
return <h2>Overview Page</h2>;
}

function Stats() {
return <h2>Stats Page</h2>;
}

function App() {
return (

53
<Router>
<div>
<nav>
<Link to="/dashboard">Go to Dashboard</Link>
</nav>
<Switch>
<Route path="/dashboard" component={Dashboard} />
</Switch>
</div>
</Router>
);
}

export default App;


Key Points:
 The Dashboard page has nested routes (like /dashboard/overview and
/dashboard/stats).
 The nested routes are rendered inside the Dashboard component using Switch and
Route.

7. Programmatic Navigation
In some cases, you may need to navigate to a different route programmatically (e.g., after a
form submission). This can be done using the useHistory hook (or history.push() method) from
React Router.
Example: Programmatic Navigation
import React from 'react';
import { useHistory } from 'react-router-dom';

function MyComponent() {
const history = useHistory();

const navigate = () => {


history.push('/new-path'); // Navigate to new path
};

return (
<div>
<button onClick={navigate}>Go to New Page</button>

54
</div>
);
}

export default MyComponent;

Conclusion
React Router is an essential library for building Single Page Applications (SPAs) in React. It allows
you to:
 Define routes for different components.
 Use dynamic routes with parameters.
 Handle programmatic navigation and redirects.
 Implement nested routes for complex layouts.
 Navigate between different pages/components without full page reloads.
With React Router, you can structure your application’s navigation in a way that is both efficient
and easy to maintain.

55

You might also like