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

Unit-5

ReactJS is an open-source JavaScript library developed by Facebook for building user interfaces, particularly single-page applications, through reusable components. It features a component-based architecture, JSX syntax, virtual DOM for efficient updates, and state management using hooks. React is easier to learn compared to Angular, which is a complete framework, and it allows for efficient code reuse and faster development due to its lightweight nature.

Uploaded by

viickyy0011
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)
5 views

Unit-5

ReactJS is an open-source JavaScript library developed by Facebook for building user interfaces, particularly single-page applications, through reusable components. It features a component-based architecture, JSX syntax, virtual DOM for efficient updates, and state management using hooks. React is easier to learn compared to Angular, which is a complete framework, and it allows for efficient code reuse and faster development due to its lightweight nature.

Uploaded by

viickyy0011
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/ 40

Unit-5

What is ReactJS?
ReactJS is a free, open-source JavaScript library for
building User Interfaces(UIs) for web
applications ,which was developed by Facebook .
It is used to build single-page applications and allows
you to create reusable UI components.

Need of react
React is an excellent tool for building websites quickly.
React works on components which makes it easy to
reuse the components in other builds. It also allows
you to create new features without having to start from
scratch, as you can reuse the codes and save time and
money as well

Features of ReactJS
 Component Based Architecture: Reusable
components of code that represents different
parts of user interface.
 JSX: JavaScript XML, a syntax extension for
JavaScript, that allows us to write HTML in
JavaScript Code.
 Virtual DOM: ReactJS uses Virtual DOM.
With Virtual DOM, only the component or part
that changes gets updated in Real DOM.
 State Management: State is managed within the
component, and when it changes, the components
re-renders.
 One Way Data Binding: Data is passed from parent
to child components through props.
 React Hooks: Hooks like useState, useEffect and
useContext.... make it easier to write more clean
and readable code.

Advantages of React
1. Easy To Learn:- React can be learned quickly and
easily because it doesn’t require special skills or
experience—just basic HTML, CSS, and JavaScript
knowledge.
2.Faster To Build:- Faster To Build Because of its
component-based approach and virtual DOM
3.Efficient Code Reuse Facility:- The major
advantage of components in this JavaScript
library is that you can re-use them on any
platform
Difference between react and angular
React and angular both are used to create single page
application using component.

React Angular

javascript typescript
React used to create Angular used to create single
single page page application using
application using component.
component.

React is a javascript Angular is a complete


library framework
React uses a virtual Angular uses a real DOM.
DOM which makes it
faster
React is smaller in size Angular is bigger because it is
and lightweight and a complete framework
therefore faster
sometime.
React depends on Angular is a complete
external libraries for framework therefore it
many complex provide built-in support for
features, so developer feature s like
has to write many routing,forms,validation, and
lines of code for HTTP requests.
complex
functionalities
React is simple to Angular is slightly difficult to
learn and more learn as it has typescript ,oops
popular than angular concept and many more
thing.
External libraries For testing we have Built-in
(Jest, React Testing tools (Karma, Jasmine)
Library)
Facebook Youtube ,Walmart,gmail,payp
airbnd,instagm, al,upwork This application are
whatapp, developed by angular
netflix .This
application are
developed by react

Simple react structure


Organizing a React project with a well-planned folder
structure is very important for readability, scalability,
and maintainability. A clear structure helps in managing
code, configurations, modules, and other assets
effectively. In this article, we are going to learn the
folder structure of the React project.

Installation of ReactJS:-
Create React App (CRA) has been officially deprecated
in 2023 and is no longer the recommended method for
starting React projects. Instead, tools
like Vite or Next.js are now preferred for creating React
applications due to better performance and modern
features. However, if you still want to use it, follow
these steps:
1. Install CRA Globally
npm install -g create-react-app
2. Verify the installation
It will globally install react app for you. To check
everything went well run the command
create-react-app --version
3.Create the React App Using CRA Command
If you’re using CRA:
Run the following command to create a React app:
npx create-react-app reactfirst
Run the React App
Start the development server by running:
npm start
Once you run the above command, a new browser tab
will open, displaying the default React page with the
React logo.
Write a program in Angular to display Hello world
Index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(<App />,
document.getElementById('root'));

App.js
import React from 'react';
function App() {
return <h1>Hello, World!</h1>;
}
export default App;

Output:-

Virtual DOM:
The Virtual DOM (VDOM) is a lightweight, in-memory
representation of the real DOM (Document Object
Model). It helps React manage UI updates more
efficiently by keeping a virtual version of the UI in
memory. When changes occur, React updates only the
necessary parts of the real DOM, instead of re-
rendering everything.

How Does the Virtual DOM Work?


Here’s a breakdown of how the Virtual DOM works:
1. Rendering the Virtual DOM: React creates a virtual
representation of the UI as a tree of JavaScript
objects.
2. Updating State: It generates a new Virtual DOM
tree to reflect the updated state when the
application state changes.
3. Diffing Algorithm: React compares the new Virtual
DOM tree with the previous one using its
efficient diffing algorithm to identify the minimal
set of changes required.
4. Updating the Real DOM: React applies only the
necessary changes to the real DOM, optimizing
rendering performance.
Advantages of the Virtual DOM
 Improved Performance: Reduces costly DOM
manipulations by batching updates.
 Simplified Development: Developers focus on
component logic, leaving optimization to React.
 Consistent Rendering: Abstracts browser-specific
rendering, ensuring uniform performance.
 Better User Experience: Faster updates lead to
smoother interactions and enhanced user
satisfaction.
Differences between Real Dom and Virtual Dom

Real DOM Virtual DOM


Virtual DOM represent
Real DOM represent
the virtual/memory
actual structure of the
representation of the
webpage.
Webpage.
DOM manipulation is very DOM manipulation is very
expensive easy
There is too much
No memory wastage
memory wastage
It updates Slow It updates fast
It can directly update It can’t update HTML
HTML directly
Creates a new DOM if the Update the JSX if the
element updates. element update
It allows us to directly It can produce about
target any specific 200,000 Virtual DOM
node (HTML element) Nodes / Second.
It is only a virtual
It represents the Ul of
representation of the
your application
DOM
React components
Components are basic building blocks of any ReactJS
there are two types of components that are created in
ReactJS.
1)functional component
2) class component
functional component:-functional components are
simple javascript functions.the functional components
return the JSX(JavaScript XML) code to render the DOM
tree.following code fragment shows the functional
component.

Example Program:-
Apple.jsx

function Apple(){
return (
<h1>This is my component.</h1>

)
}
export default Apple;

App.js
import logo from './logo.svg';
import './App.css';
import Apple from './Apple';
function App() {
return (
<div className="App">
<Apple />
</div>
);
}
export default App;
output:-
2)class component:-
To define the class component we have to first create a
class and extend ReactComponent class.
Class components are ES6 classes that return
JSX .Below is a class component which is similar to
Welcome function as given in Functional component.

Example program:-
Welcome.js
import React,{Component} from 'react';
class Welcome extends Component{
render() {
return <h1>welcome to lab </h1>
}
}
export default Welcome;

App.js
import './App.css';
import Welcome from './components/Welcome';
function App() {
return (
<div className="Welcome">
<Welcome />
</div>
);
}
export default App;
Props:-
The props stand for properties.These are the
arguments that are passed to the react components.
// App.js
import React from 'react';
import Greeting from './Greeting';

function App() {
return (
<div>
<h1>Welcome to React Props Example</h1>
<Greeting name="John" />
</div>
);
}
export default App;

Greeting.js (Child Component)


import React from 'react';
function Greeting(props) {
return <p>Hello, {props.name}!</p>;
}
export default Greeting;

Data Flow in React JS:


React follows a unidirectional data flow, meaning that
data flows in a single direction through the
components. This helps in maintaining a predictable
state and making it easier to understand how changes
affect the application. In React we can pass props from
Parent component to child and with the help of
callback can also pass props from child to parent.

1. Parent to Child:
Data is passed from parent components to child
components through props. The parent component
owns the state, and it passes down relevant data to its
child components as props.
Props (short for "properties") in React are a mechanism
for passing data from a parent component to its child
component as a set of read-only attributes.
Example program: Sending the data from parent to
child as "Hello, this is data from the parent to child".

import React, { useState } from 'react';


import ChildComponent from './ChildComponent';
function ParentComponent() {
const [data, setData] = useState('"Hello, this is the
data from the parent to child".!');
return <ChildComponent data={data} />;
}

export default ParentComponent;


Output:
2. Child to Parent:
To communicate from child to parent, the parent can
pass down a callback function as a prop to the child.
The child can then invoke this function to send data
back to the parent.
Example program: Sending the data from child to
parent as "Hello, this is data from the child to parent".

import React, { useState } from "react";


import ChildComponent from "./ChildComponent";
function ParentComponent() {
const [dataFromChild, setDataFromChild] =
useState("");
const handleDataFromChild = (data) => {
setDataFromChild(data);
};
return (
<div>
<p>Data from child: {dataFromChild}</p>
<ChildComponent
sendDataToParent={handleDataFromChild} />
</div>
);
}

export default ParentComponent;


Output:

State Management in React:-


React JS State is a way to store and manage the
information or data while creating a React
Application. The state is a JavaScript object that
contains the real-time data or information on the
webpage. The state in React is an instance of the
React Component that can be defined as an object of
a set of observable properties that control the
behaviour of the component. In other words, the
State of a component is an object that holds some
information that may change over the lifetime of the
component.
Approach 1: Manage states using Hooks
Hooks were introduced in React 16.8, which makes a
great revolution in functional components by helping
them to manage state and lifecycle features.
useState is a fundamental hook by which we can
easily able to manage states. It enables us to create
and change state variables within our components,
eliminating the need for class components.
Syntax:
const [state, setState] = useState(<default value>);
Example program:- In this example we will see how we
can manage state with the help of useState Hook.

import React, { useState } from 'react';


function App() {
const [counter, setCounter] = useState(0);

function handleUpdateCounter() {
setCounter(counter + 1);
}
return (
<>
<h1>Counter value: {counter}</h1>
<button
onClick={handleUpdateCounter}>Change</button>
</>
);
}
export default App;
App.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
const
root=ReactDOM.createRoot(document.getElementById
('root'));
root.render(
<App />
);

Rendering and life cycle methods in react:-


The React lifecycle refers to the different phases a component
goes through during its time in a React application. These
phases allow you to run specific code at key moments in a
component’s life, such as when it’s created, updated, or
removed from the screen.
Here are the three main phases of the React component lifecycle
 Mounting: Initializes, renders, and mounts the
component (componentDidMount()).
 Updating: Handles state/prop changes, re-renders,
and updates (componentDidUpdate()).
 Unmounting: Cleans up before removal
(componentWillUnmount()).
Phases of Lifecycle in React Components
1. Mounting
Mounting refers to the process of creating and
inserting a component into the DOM for the first time
in a React application. During mounting, React
initializes the component, sets up its internal state (if
any), and inserts it into the DOM.
 constructor
 getDerivedStateFromProps
 render()
 componentDidMount()
constructor():-
Method to initialize state and bind methods. Executed
before the component is mounted.
constructor(props) {
super(props); // Always call super(props) before
using this.props
this.state = {
count: 0,
};
console.log("Constructor called");
}
getDerivedStateFromProps(props, state):-
Used for updating the state based on props. Executed
before every render.
static getDerivedStateFromProps(props, state) {
if (props.value !== state.value) {
return { value: props.value };
}
return null; // No changes to state
}
render():-
Responsible for rendering JSX and updating the DOM.
render() {
return (
<div>
<h1>Hello, React Lifecycle!</h1>
</div>
);
}
componentDidMount() :-
This function is invoked right after the component is
mounted on the DOM, i.e. this function gets invoked
once after the render() function is executed for the first
time.
componentDidMount() {
console.log("Component has been mounted");

fetch("https://api.example.com/data")
.then(response => response.json())
.then(data => this.setState({ data }));
}
2. Updation
Updating refers to the process of a component being
re-rendered due to changes in its state or props. This
phase occurs whenever a component’s internal state is
modified or its parent component passes new props.
When an update happens, React re-renders the
component to reflect the changes and ensures that the
DOM is updated accordingly.
 getDerivedStateFromProps
 setState() Function
 shouldComponentUpdate()
 getSnapshotBeforeUpdate() Method
 componentDidUpdate()
getDerivedStateFromProps:-
getDerivedStateFromProps(props, state) is a static
method that is called just before the render() method
in both the mounting and updating phase in React. It
takes updated props and the current state as
arguments.
static getDerivedStateFromProps(props, state) {
if (props.name !== state.name) {
return { name: props.name };
}
return null;
}
setState():-
This is not particularly a Lifecycle function and can be
invoked explicitly at any instant. This function is used to
update the state of a component. You may refer to this
article for detailed information.
this.setState((prevState, props) => ({
counter: prevState.count + props.diff
}));
shouldComponentUpdate():-
shouldComponentUpdate() Is a lifecycle method in
React class components that determines whether a
component should re-render. It compares the current
and next props/states and returns true if the
component should update or false if it should not.
shouldComponentUpdate(nextProps, nextState)
It returns true or false, if false, then
render(), componentWillUpdate(), and componentDid
Update() method does not get invoked.
getSnapshotBeforeUpdate():-
The getSnapshotBeforeUpdate() method is invoked just
before the DOM is being rendered. It is used to store
the previous values of the state after the DOM is
updated.
getSnapshotBeforeUpdate(prevProps, prevState)
componentDidUpdate():-
Similarly, this function is invoked after the component
is rendered, i.e., this function gets invoked once after
the render() function is executed after the updation of
State or Props.
componentDidUpdate(prevProps, prevState, snapshot)
3. Unmounting
This is the final phase of the lifecycle of the
component, which is the phase of unmounting the
component from the DOM. The following function is
the sole member of this phase.
componentWillUnmount():-
This function is invoked before the component is finally
unmounted from the DOM, i.e., this function gets
invoked once before the component is removed from
the page, and this denotes the end of the lifecycle.
Implementing the Component Lifecycle methods
Let us now see one final example to finish the article
while revising what’s discussed above.
First, create a react app and edit your index.js file from
the src folder.
// Filename - src/index.js:
import React from "react";
import ReactDOM from 'react-dom';
class Test extends React.Component {
constructor(props) {
super(props);
this.state = { hello: "World!" };
}
componentDidMount() {
console.log("componentDidMount()");
}
changeState() {
this.setState({ hello: "how are you!" });
}
render() {
return (
<div>
<h1>
Hai , Hello
{this.state.hello}
</h1>
<h2>
<a
onClick={this.changeState.bind(
this
)}
>
Press Here!
</a>
</h2>
</div>
);
}
shouldComponentUpdate(nextProps, nextState) {
console.log("shouldComponentUpdate()");
return true;
}
componentDidUpdate() {
console.log("componentDidUpdate()");
}
}
const root = ReactDOM.createRoot(
document.getElementById("root")
);
root.render(<Test />);

Working with forms in react


React Forms are an important part of most web
applications. They allow users to input data and
interact with the application. Forms are used to collect
the data from the user and process it as required
whether in login-signup forms or surveys etc.

// Filename - App.js

import React, { useState } from "react";


export default function App() {
const [value, setValue] = useState("");

return (
<div>
<h2>ReactJs Form</h2>
<form>
<label>
Input Field:-
<input
value={value}
onChange={(e) => {
setValue(e.value);
}}
/>
</label>
</form>
</div>
);
}
Integrating third party libraries
Integrating React JS with other libraries is a common practice
in web development to utilize the functionality of those
libraries. React JS is itself a JavaScript library. ReactJS
workflow is like first importing the thing or component and
then using it in your code, you can export your components
and import wherever you like in your files. There are so many
ReactJS libraries or JavaScript libraries available like uuid,
toastify, etc. They can be easily integrated into your ReactJS
app.import React from 'react';

// Filename - App.js

import React from "react";


import { v4 } from "uuid";

export default function App() {


const id = v4();
return (
<div>
<h1>Your unique id is :</h1>
<h2>{id}</h2>
<h3>Refresh for new id</h3>
</div>
);
}

Routing in react
React Router is a standard library for creating dynamic
routes and navigation in React JS Applications. It allows
you to manage navigation in your app by defining
routes that connect the URL paths to specific
components.
With React Router, you can implement different views
for different parts of your application without the need
for a full-page refresh. This is a key feature of single-
page applications (SPAs), where only the necessary
content is updated as the user navigates.
Types of React Routers:-
There are three types of routers in React:
1. BrowserRouter: The BrowserRouter is the most
commonly used router for modern React
applications. It uses the HTML5 History API to
manage routing, which allows the URL to be
dynamically updated while ensuring the browser’s
address bar and history are in sync.
2. HashRouter: The HashRouter is useful when you
want to use a URL hash (#) for routing, rather than
the HTML5 history API. It doesn’t require server
configuration and works even if the server doesn’t
support URL rewriting.
3. MemoryRouter: The MemoryRouter is used in
non-browser environments, such as in React
Native or when running tests.
Components of React Router:-
Here are the main components used in React Router:
1. BrowserRouter and HashRouter
 BrowserRouter: Uses the HTML5 history API to
keep your UI in sync with the URL.
 HashRouter: Uses the hash portion of the URL (i.e.,
window.location.hash) to keep your UI in sync with
the URL.
<BrowserRouter>
(/* Your routes go here */}
</BrowserRouter>
2. Routes and Route
 Routes: A container for all your route definitions.
 Route: Defines a single route with a path and the
component to render.
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
3. Link and NavLink
 Link: Creates navigational links in your application.
 NavLink: Similar to Link but provides additional
styling attributes when the link is active.
<nav>
<NavLink to="/"
activeClassName="active">Home</NavLink>
<Link to="/about">About</Link>
</nav>

Example program:-
import React from 'react';
import { BrowserRouter as Router, Routes, Route, Link }
from 'react-router-dom';
function Home() {
return <h2>Home Page</h2>;
}
function About() {
return <h2>About Page</h2>;
}
function Contact() {
return <h2>Contact Page</h2>;
}
function App() {
return (
<Router>
<nav>
<Link to="/">Home</Link> |{" "}
<Link to="/about">About</Link> |{" "}
<Link to="/contact">Contact</Link>
</nav>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/contact" element={<Contact />} />
</Routes>
</Router>
);
}
export default App;

Uses of React Router


1. Navigation and Routing: React Router provides a
declarative way to navigate between different
views or pages in a React application. It allows
users to switch between views without refreshing
the entire page.
2. Dynamic Routing: React Router supports dynamic
routing, which means routes can change based on
the application’s state or data, making it possible
to handle complex navigation scenarios.
3. URL Management: React Router helps manage the
URLs in your application, allowing for deep linking,
bookmarkable URLs, and maintaining the
browser’s history stack.
4. Component-Based Approach: Routing is handled
through components, making it easy to compose
routes and navigation in a modular and reusable
way.
5. Handling Nested Routes: React Router allows the
creation of nested routes, which enables a more
organized and structured approach to rendering
content. This is particularly useful for larger
applications with a complex structure.

You might also like