UNIT-V-REACT.JS
UNIT-V-REACT.JS
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>
);
}
function Header() {
return (
<header>
<h1>My React Application</h1>
</header>
);
}
5
src/components/Footer.js
import React from 'react';
function Footer() {
return (
<footer>
<p>© 2025 My React App</p>
</footer>
);
}
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.
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:
function Counter() {
const [count, setCount] = useState(0); // State hook to manage the count value
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
</div>
);
}
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.
increment = () => {
this.setState({ count: this.state.count + 1 });
};
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={this.increment}>Increment</button>
</div>
);
}
}
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.
function App() {
return (
<div>
<Greeting name="John" />
<Greeting name="Alice" />
</div>
);
}
12
Child Component (Greeting.js):
import React from 'react';
function Greeting(props) {
return <h1>Hello, {props.name}!</h1>;
}
function Counter() {
const [count, setCount] = useState(0); // Declare state with the useState hook
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
</div>
);
}
13
import React, { Component } from 'react';
increment = () => {
this.setState({ count: this.state.count + 1 });
};
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={this.increment}>Increment</button>
</div>
);
}
}
function ClickMe() {
const [message, setMessage] = useState('Click the button');
14
return (
<div>
<p>{message}</p>
<button onClick={handleClick}>Click Me</button>
</div>
);
}
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.
15
function Welcome() {
return <h1>Hello, Welcome to React!</h1>;
}
function App() {
return (
<div>
<Welcome /> {/* Rendering the Welcome component */}
</div>
);
}
function Greeting(props) {
return <h1>Hello, {props.name}!</h1>;
}
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>
);
}
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';
18
class App extends React.Component {
render() {
return (
<div>
<Greeting name="Alice" />
<Greeting name="Bob" />
</div>
);
}
}
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
);
}
}
function Counter() {
const [count, setCount] = useState(0); // Initializing state
20
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
</div>
);
}
function App() {
return (
<div>
<Counter /> {/* Rendering the stateful functional component */}
</div>
);
}
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.
function App() {
return (
<div>
<Greeting name="Alice" />
<Greeting name="Bob" />
</div>
);
}
function Greeting(props) {
return <h1>Hello, {props.name}!</h1>;
22
}
function Counter() {
const [count, setCount] = useState(0); // useState hook for state management
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
</div>
);
}
23
import React, { Component } from 'react';
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>
);
}
}
24
import Greeting from './Greeting';
function App() {
const [name, setName] = useState("Alice");
return (
<div>
<Greeting name={name} />
<button onClick={changeName}>Change Name</button>
</div>
);
}
function Greeting(props) {
return <h1>Hello, {props.name}!</h1>;
}
25
function App() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<Button onClick={incrementCount} />
</div>
);
}
function Button(props) {
return <button onClick={props.onClick}>Increment</button>;
}
26
import Input from './Input';
import Display from './Display';
function App() {
const [text, setText] = useState("");
return (
<div>
<Input onTextChange={handleTextChange} />
<Display text={text} />
</div>
);
}
function Input(props) {
const handleChange = (event) => {
props.onTextChange(event.target.value); // Passing data to parent
};
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.
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.
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>;
}
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. }
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");
}
}
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);
return (
<div>
<h1>{count}</h1>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
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.
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('');
34
};
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>
);
}
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();
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>
);
}
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({});
37
};
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>
);
}
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.
function Form() {
const [formData, setFormData] = useState({
name: '',
email: '',
password: ''
});
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>
);
}
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);
return (
<form onSubmit={handleSubmit}>
<label>
Choose a file:
<input type="file" onChange={handleFileChange} />
</label>
<br />
<button type="submit">Submit</button>
</form>
);
}
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.
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>
);
}
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>
);
}
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>
);
}
function App() {
return (
<div className="App">
<Alert variant="success">This is a success alert!</Alert>
<Button variant="primary">Click Me</Button>
</div>
);
}
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();
}
}, []);
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.
function Home() {
return <h1>Home Page</h1>;
}
48
// About.js
import React from 'react';
function About() {
return <h1>About Page</h1>;
}
// Contact.js
import React from 'react';
function Contact() {
return <h1>Contact Page</h1>;
}
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>
function User() {
// Accessing the dynamic parameter (userId)
const { userId } = useParams();
50
return <h1>User ID: {userId}</h1>;
}
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>
);
}
51
/user/:userId: The colon (:) syntax defines a parameter in the URL. React Router will
treat this as a dynamic route.
function SubmitForm() {
const [submitted, setSubmitted] = useState(false);
if (submitted) {
// Redirect to a success page
return <Redirect to="/success" />;
}
return (
<div>
<button onClick={handleSubmit}>Submit</button>
</div>
);
}
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>
);
}
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();
return (
<div>
<button onClick={navigate}>Go to New Page</button>
54
</div>
);
}
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