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

Unit -V (React)

Uploaded by

Jaya Prakash
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views

Unit -V (React)

Uploaded by

Jaya Prakash
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 83

Unit -V (react)

• React:
• Need of React, Simple React Structure, The Virtual
DOM, React Components, Introducing React
Components, Creating Components in React, Data and
Data Flow in React, Rendering and Life Cycle Methods
in React, Working with forms in React, integrating third
party libraries, Routing in React.
What is React?
• A JavaScript library for building user interfaces (UIs)

• Developed and maintained by Facebook

• Focuses on building fast, dynamic, and interactive


web applications

• Allows developers to create reusable UI


components
Need of React
•React is a popular JavaScript library for building user interfaces, especially for single-page applications (SPAs)
where the user experience is dynamic and responsive. It was developed by Facebook and is now widely used in
web development due to its ease of use, flexibility, and large community support.
•1. Component-Based Architecture
 Reusability: React allows developers to build UI components that can be reused throughout the application,
reducing duplication and making code easier to maintain.
 Modularity: Each component can handle a specific piece of functionality, which makes the application
easier to scale and manage.
•2. Declarative Syntax
 Developers simply describe what the UI should look like at any point in time, and React takes care of
updating and rendering the UI to match that state.
•3. Efficient Rendering (Virtual DOM)
 React uses a virtual DOM to optimize rendering performance. Instead of directly manipulating the DOM,
React updates a virtual representation of the DOM in memory, and then efficiently updates the real DOM
based on the differences.This minimizes the number of DOM operations, making applications faster and
more responsive.
Need of React

•4. Unidirectional Data Flow


 In React, data flows in one direction—from parent to child components. This makes it easier to track how
data changes in an app and leads to more predictable behavior.
 5. Large Ecosystem
• React has a massive ecosystem of libraries, tools, and resources. Popular libraries like React Router (for
routing), Redux (for state management), and Next.js (for server-side rendering and static site generation)
integrate seamlessly with React.
• 6. Cross-Platform Development
 React Native, which allows for building mobile apps using the same React principles, is a huge benefit.
Developers can reuse much of their web development knowledge and codebase for mobile development.
This makes it easier to create both web and mobile applications while maintaining a consistent
development experience.
•7. Strong Community and Support
 React has a large and active community of developers, which means lots of tutorials, documentation, open-
source contributions, and answers to common problems.
Need of React
•8. Easier Debugging with DevTools
 React has a built-in React Developer Tools extension that allows developers to inspect the
component tree, manage state, and track props changes, making debugging easier.
•9. Easy Integration with Other Libraries and Frameworks
 React can be integrated with other libraries and frameworks, allowing developers to mix and
match tools to suit their specific needs. For instance, it can be paired with back-end technologies
like Node.js, Django, or Ruby on Rails.
Core Concepts of React

1.JSX (JavaScript XML):


1.A syntax extension that allows you to write HTML-like code within
JavaScript.
2.Converts JSX code into React elements.
2.Components:
1.Building blocks of a React application.
2.Components can be either class-based or functional.
3.State and Props:
1.State: Data managed inside a component, can change over time.
2.Props: Inputs to a component from a parent component.
4.Event Handling:
1.React allows handling events like clicks, keyboard input, etc., in a
declarative way.
JSX Syntax Example1
import React from 'react';
function Greeting() {
return (
<div>
<h1>Hello, World!</h1>,
<h1>cse1 students</h1>
</div>
);
}
export default Greeting;
• JSX allows HTML to be written in JavaScript.
• React automatically converts JSX into JavaScript.
JSX Syntax Example2
import React from 'react’;
class App {
render(){
return (
<div>
<h1>Hello, World!</h1>,
<h1>cse1 students</h1>
</div>
);
}
}
export default App;
Document Object Model (DOM)
The Virtual DOM
• React keeps a virtual DOM in memory, which is a
lightweight representation of the real DOM.
• When the state of a component changes, React updates the
virtual DOM.
• React compares the virtual DOM with the real DOM (a
process called "reconciliation").
• Only the parts of the DOM that have changed are updated,
making the app more efficient.
The Virtual DOM
• What is the Virtual DOM?
• A lightweight copy of the actual DOM that React maintains in
memory.
• React updates the Virtual DOM first, then compares it to the
real DOM to update only changed elements.
• Why Use the Virtual DOM?
• Improves performance by minimizing DOM manipulation.
• React can batch updates, optimizing rendering.
• Reconciliation Process:
• React compares the Virtual DOM with the real DOM using an
algorithm called reconciliation(diff algorithm).
• It then updates the real DOM efficiently by making only
necessary changes.
The Virtual DOM
Unidirectional Data Flow

• Data flows in one direction: from parent components to


child components.
• This makes it easier to track and debug changes in your
application.
Unidirectional Data Flow

function Parent() {
const [name, setName] = useState('John');
return <Child name={name} />;
}

function Child(props) {
return <h1>Hello, {props.name}</h1>;
}
Benefits:
• Simpler data management.
• Easier to trace bugs as data changes happen in a predictable
manner.
Simple React Structure

•Components— Encapsulated units of functionality that are the primary


unit in React. They utilize data (properties and state) to render your UI as
output; Certain types of React components also provide a set of lifecycle
methods that you can hook into. The rendering process (outputting and
updating a UI based on your data) is predictable in React, and your
components can hook into it using React’s APIs.
•React libraries— React uses a set of core libraries. The core React
library works with the reactdom and reactnative libraries and is
focused on component specification and definition. It allows you to build a
tree of components that a renderer for the browser or another platform
can use. Reactdom is one such renderer and is aimed at browser
environments and serverside rendering. The React Native libraries focus
on native platforms and let you create React applications for iOS,
Android, and other platforms.
Simple React Structure

•Thirdparty libraries— React doesn’t come with tools for data modeling,
HTTP calls, styling libraries, or other common aspects of a frontend
application. This leaves you free to use additional code, modules, or other
tools you prefer in your application. And even though these common
technologies don’t come bundled with React, the broader ecosystem
around React is full of incredibly useful libraries.
•Running a React application— Your React application runs on the
platform you’re building for. It focuses on the web platform and builds a
browser and server based application, but other projects like React
Native and React VR open the possibility of your app running on other
platforms.
Simple React Structure
Full Project Structure
• After running the above commands, your project structure should look something like
this:
• hello-world/
• ├── node_modules/
• ├── public/
• │ └── index.html
• ├── src/
• │ ├── App.css
• │ ├── App.js
• │ ├── index.js
• │ └── logo.svg
• ├── package.json
• ├── package-lock.json
• └── README.md
• • The src/App.js file contains the main code for your app.
• • index.js is where React is hooked into the HTML DOM.
React Lifecycle Methods (Class Components)

•What are Lifecycle Methods?


•Special methods that are called at specific stages in a
component’s life.
•Lifecycle methods are mainly used for managing side effects
(e.g., fetching data).
•Common Lifecycle Methods:
•componentDidMount(): Called after the component has
been rendered to the screen.
•componentDidUpdate(): Called after updates to the
component.
•componentWillUnmount(): Called before the component is
removed from the DOM.
React Lifecycle Methods (Class Components)

class Example extends React.Component {


componentDidMount() {
console.log('Component mounted');
}
render() {
return <h1>Component</h1>;
}
}
Setting Up React
•Create React App: A tool to create a new React
application quickly.
•Command: npx create-react-app my-app
•Folder Structure:
•public/ – Publicly accessible files.
•src/ – Application source code (components, styles,
etc.).
•Running the Application:
•Command: npm start
•Runs the application on http://localhost:3000
Prerequisites
•Make sure you have the following installed:

1. Node.js and npm (Node Package Manager). You can check if these are installed by
running the following commands in your terminal:
• node -v
• npm -v
•If you don't have Node.js and npm installed, you can download them from nodejs.org.
Step-by-Step Guide FOR CREATING "Hello World" React application

•1. Create a New React App Using Create React App

•Run the following command in your terminal:

•A)npm install –g create-react-app

•B)Create-react-app hello-world

(or)

•A) npx create-react-app hello-world

•This will create a new directory called hello-world and set up a boilerplate React application.

•2. Navigate to Your Project Directory

•Once the setup is complete, go into the hello-world directory:

•cd hello-world
Step-by-Step Guide FOR CREATING "Hello World" React application

•3. Open src/App.js: The App.js file should look something like this:
import React from 'react';
import './App.css';
function App() {
return (
<div className="App">
<h1>Hello World</h1>
</div>
);
}
export default App;
Step-by-Step Guide FOR CREATING "Hello World" React application

•4. Start the Development Server

•Now that your App.js is set up, start the development server to view your application.

•Run:

•npm start

•This will start the server, and you should see your "Hello World" application in your browser
at http://localhost:3000/.
OUTPUT
Components in React
• The entire application is divided into a small logical group of code, which is known as
components.
• A Component is considered as the core building blocks of a React application. It
makes the task of building UIs much easier.
• Each component exists in the same space, but they work independently from one
another and merge all in a parent component, which will be the final UI of your
application.
• Every React component have their own structure, methods as well as APIs. They can
be reusable as per your need.
• For better understanding, consider the entire UI as a tree. Here, the root is the starting
component, and each of the other pieces becomes branches, which are further divided
into sub-branches.
• In ReactJS, we have mainly two types of components.
1.Functional Components
2.Class Components
Components in React

•Functional Components: Stateless, simpler syntax.


•Class Components: Can hold and manage state,
lifecycle methods.
Functional Components in React

• In React, function components are a way to write components that only


contain a render method and don't have their own state.
• They are simply JavaScript functions that may or may not receive data as
parameters. We can create a function that takes props(properties) as
input and returns what should be rendered.
• Add extension ES7+ React in vscode.
• Use rfc.
function WelcomeMessage(props) {
return <h1>Welcome to the , {props.name}</h1>;
}
• The functional component is also known as a stateless component
because they do not hold or manage state.
Class Components in React
• Class components are more complex than functional components. It requires you to
extend from React. Component and create a render function which returns a React
element. You can pass data from one class to other class components. You can create a
class by defining a class that extends Component and has a render function.
• Add extension ES7+ React in vscode.
• Use rfc.
class MyComponent extends React.Component {
render() {
return (
<div>This is main component.</div>
);
}
}
• The class component is also known as a stateful component because they can hold or
manage local state.
Example Function Based
Component (FBC.js)
//FBC.js
import React from 'react'

export default function FBC() {


return (
<div> function based component</div>
)
}
Example of a Class
Component(src/CBC.js))
//CBC.js

import React, { Component } from 'react'


export default class CBC extends Component {
render() {
return (
<div>class based component </div>
)
}
}
Example of components(src/App.js))
import CBC from "./CBC";
import FBC from "./FBC";
function App() {
return (
<div>
<h1>hello world- main component</h1>
<CBC></CBC>
<FBC></FBC>
</div>

);
}
export default App;
Example of components(output)
Data and Data Flow in React
• Mutable and immutable state
• state- mutable & props- immutable
• Stateful and stateless components
• Class based component- stateful
• Functional based component-
stateless
• Component communication
• One way data flow
• Parent to child communication
State and Props in Action
• State: Can be updated and triggers re-rendering. State is data that
changes over time, managed within the component. State is
mutable and can trigger re-renders when updated.
state - in class component
useState - in functional component

• Props: Passed from parent to child, immutable inside the


component.
State and Props
•Props:
•Props are inputs to a component, passed down from
parent to child.
•Immutable inside the child component.
•Used to customize a component's behavior or
appearance.
•Example:
jsx
function Greet(props)
{ return
<h1>Hello, {props.name} </h1>;
}
React State

• The state is an updatable structure that is used to contain data or information about
the component.
• The state in a component can change over time. The change in state over time can
happen as a response to user action or system event.
• A component with the state is known as stateful components.
• It is the heart of the react component which determines the behavior of the component
and how it will render. They are also responsible for making a component dynamic and
interactive.
• A state must be kept as simple as possible. It can be set by using the setState() method
and calling setState() method triggers UI updates.
• A state represents the component's local state or information. It can only be accessed or
modified inside the component or by the component directly.
• To set an initial state before any interaction occurs, we need to use the getInitialState()
method.
React State

• Defining State
• To define a state, you have to first declare a default set of values for defining the
component's initial state.
• To do this, add a class constructor which assigns an initial state using this.state.
• The 'this.state' property can be rendered inside render() method.
Example of State in a Class Component:
import React, { useState } from 'react’; return (
<div style={{ textAlign: 'center',
function Counter() { marginTop: '50px' }}>
// Declare a state variable 'count' and a <h1>Counter: {count}</h1>
function to update it 'setCount' <button
const [count, setCount] = useState(0); onClick={decrement}>Decrement<
/button>
// Function to handle increment <button
const increment = () => { onClick={increment}>Increment</b
setCount(count + 1);
utton>
</div>
};
);
// Function to handle decrement
}
const decrement = () => { export default Counter;
setCount(count - 1);
};
Example of State in a Class Component:
useState Hook:
useState(0) initializes the count state with a value of
0.
setCount is a function used to update the value of
count.
State Updates:
The increment function updates the state by adding 1
to count.
The decrement function updates the state by
subtracting 1 from count.
Dynamic Rendering:
The count value is displayed dynamically in the
<h1> element.
When the state is updated (via setCount), React re-
renders the component to reflect the new state.
Output:
When you click the Increment button, the number
increases. When you click the Decrement button, the
React Hooks (Functional
Components)
• Why Hooks?
• Hooks allow you to use state and lifecycle features in
functional components.
• useState: Manages state in a functional component.
• useEffect: Handles side effects (e.g., fetching data, event
listeners).
React Props
• In React, props (short for "properties") are a way to pass data from a parent
component to a child component.
• Props are read-only, meaning the child component cannot modify them—
they're immutable.
• It is an object which stores the value of attributes of a tag and work similar to
the HTML attributes.
• It gives a way to pass data from one component to other components.
• It is similar to function arguments. Props are passed to the component in the
same way as arguments passed in a function.
• Props are immutable so we cannot modify the props from inside the
component. Inside the components, we can add attributes called props.
• These attributes are available in the component as this.props and can be used
to render dynamic data in our render method.
• When you need immutable data in the component, you have to add props to
reactDom.render() method in the main.js file of your ReactJS project and
used it inside the component in which you need.
React Props(app.js- parent component)
import React from 'react';
import Greeting from './Greeting';
function App() {
return (
<div style={{ textAlign: 'center', marginTop: '50px' }}>
<h1>React Props Example</h1>
{/* Passing props to the Greeting component */}
<Greeting name="Alice" id="111" />
<Greeting name="Bob" id="222"/>
<Greeting name="Charlie" id="333"/>

</div>
);
}
export default App;
React Props(Greeting.js- child component)

import React from 'react';

function Greeting(props) {

return(

<h2>Hello, Your name:{props.name} and id:{props.id}


</h2>

);
React Props(output)
React Props(output)
Explanation:
Passing Props:
In App.js, the Greeting component is used three times with different values for
the name prop (e.g., name="Alice").
This allows Greeting to dynamically render different content based on the props
it receives.
Using Props:
In Greeting.js, the props object is used to access the name property
(props.name).
The value of props.name is injected into the JSX using curly braces {}.
Output: When the application runs, the output will be:

React Props Example


Hello, Alice!
Hello, Bob!
Hello, Charlie!
React life cycle methods- phases
React Lifecycle Phases

• React components (class-based) have specific lifecycle methods


that are called at different stages of a component's existence. The
React lifecycle is divided into different phases:
• Initialization phase: This is the stage where the component is
constructed with the given Props and default state. This is done in
the constructor of a Component Class.
• Mounting Phase: This phase begins when a component is
created and inserted into the DOM.
• Updating Phase: This occurs when a component is re-rendered
due to changes in props or state.
• Unmounting Phase: This is the final phase when a component is
removed from the DOM.
• Error Handling : This occurs in case of errors.
The life cycle of a React component
The life cycle of a React component refers to the phases a component
goes through during its existence, from creation to removal from the
DOM.
1. Initialization Phase
This is the setup phase where the component is being created.
Constructor (optional):
Used to initialize the component's state and bind methods.

Example:
constructor(props) {
super(props);
this.state = { counter: 0 };
}
2. Mounting (When the component is added to the DOM)

• constructor():
• Initializes state and binds methods.
• Avoid heavy logic here; use it for simple initialization.
• static getDerivedStateFromProps(props, state):
• Syncs state with props before rendering.
• render():
• Returns the JSX to be rendered.
• componentDidMount():
• Invoked after the component is rendered into the DOM.
• Perfect for API calls, subscriptions, or DOM manipulations.
3. Updating (When props or state change)
•shouldComponentUpdate(nextProps, nextState):
•Determines if the component should re-render (used for
optimization).

•getSnapshotBeforeUpdate(prevProps, prevState):
•Captures a snapshot of the DOM before changes (used for
scrolling, etc.).

•componentDidUpdate(prevProps, prevState, snapshot):


•Invoked after updates are flushed to the DOM.
•Useful for further updates or re-fetching data.
Example:
componentDidUpdate(prevProps, prevState) {
if (prevState.counter !== this.state.counter) {
console.log('Counter updated!');
}
4. Unmounting (When the component is removed
from the DOM)

• Unmounting (When the component is removed from the


DOM)
componentWillUnmount():
• Called before a component is unmounted and destroyed.
• Use this for cleanup (e.g., canceling timers, removing
event listeners).
Example:
componentWillUnmount() {
clearInterval(this.timer);
}
5. Error Handling Phase
Triggered when there are errors during rendering or in
lifecycle methods of child components.

componentDidCatch(error, info) (used frequently):


Logs error information.

Example:
componentDidCatch(error, info) {
console.error("Error caught:", error, info);
}
Life cycle method(app.js)
import React from 'react';
class LifeCycleDemo extends React.Component {
// Constructor: Initialize state or bind methods
constructor(props) {
super(props);
this.state = {
count: 0,
};
console.log('Constructor: Component is being created.');
}
// Called after the component is added to the DOM
componentDidMount() {
console.log('componentDidMount: Component has been added to the DOM.');
}
// Called when the component is updated (e.g., state or props change)
componentDidUpdate(prevProps, prevState) {
console.log('componentDidUpdate: Component has been updated.');
console.log('Previous state:', prevState);
console.log('Current state:', this.state);
}
Life cycle method(app.js)
// Called just before the component is removed from the DOM
componentWillUnmount() {
console.log('componentWillUnmount: Component is being removed.');
}
// Event handler to update state
handleIncrement = () => {
this.setState((prevState) => ({ count: prevState.count + 1 }));
};
render() {
console.log('Render: Rendering the component.');
return (
<div>
<h1>React Lifecycle Demo</h1>
<p>Count: {this.state.count}</p>
<button onClick={this.handleIncrement}>Increment</button>
</div>
);
}
}
export default LifeCycleDemo;
Life cycle method(app.js)
Working with forms in React
• Using forms in React

• Controlled and uncontrolled form components in


React

• Validating form data in React


Working with forms in React (React Forms)
• Forms are an integral part of any modern web application.
• It allows the users to interact with the application as well as gather
information from the users.
• Forms can perform many tasks that depend on the nature of your business
requirements and logic such as authentication of the user, adding user,
searching, filtering, booking, ordering, etc.
• A form can contain text fields, buttons, checkbox, radio button, etc.
• Creating Form
• React offers a stateful, reactive approach to build a form. The component rather
than the DOM usually handles the React form. In React, the form is usually
implemented by using controlled components.
• There are mainly two types of form input in React.
1.Uncontrolled component
2.Controlled component
Working with forms in React
• Uncontrolled component
• The uncontrolled input is similar to the traditional HTML form inputs.
• The DOM itself handles the form data.
• Here, the HTML elements maintain their own state that will be updated when
the input value changes.
• To write an uncontrolled component, you need to use a ref to get form
values from the DOM.
• In other words, there is no need to write an event handler for every state
update.
• You can use a ref to access the input field value of the form from the DOM
Working with forms in React
• Controlled Component
• In HTML, form elements typically maintain their own state and update it
according to the user input. In the controlled component, the input form
element is handled by the component rather than the DOM. Here, the mutable
state is kept in the state property and will be updated only
with setState() method.
• Controlled components have functions that govern the data passing into them on
every onChange event, rather than grabbing the data only once, e.g., when
you click a submit button. This data is then saved to state and updated with
setState() method. This makes component have better control over the form
elements and data.
• A controlled component takes its current value through props and notifies the
changes through callbacks like an onChange event. A parent component
"controls" this changes by handling the callback and managing its own state and
then passing the new values as props to the controlled component. It is also
called as a "dumb component."
Working with forms in React
SN Controlled Uncontrolled
It does not maintain its internal
1. It maintains its internal states.
state.

Here, data is controlled by the


2. Here, data is controlled by the DOM itself.
parent component.

It accepts its current value as a


3. It uses a ref for their current values.
prop.

4. It allows validation control. It does not allow validation control.

It has better control over the It has limited control over the form
5.
form elements and data. elements and data.
Validating form data in React
• Validating form data in React

• Form validation in React ensures user inputs are correct, complete, and meet required
criteria before submission.
• Types of Validation
• Client-side Validation:
• Performed in the browser.
• Provides instant feedback to the user.
• Reduces server load by catching errors early.
• Server-side Validation:
• Ensures security and data integrity.
• Always validate on the server, even if client-side validation exists.
• Hybrid Approach:
• Combines client and server validation for a robust solution.
Validating form data in React
• Common Validation Rules
• Required Fields: Ensure the user doesn't leave a field empty.
• Format Validation: Check specific patterns (e.g., email,
phone numbers).
• Length Validation: Ensure input meets length requirements
(e.g., password length).
• Range Validation: For numeric or date inputs, validate
min/max limits.
• Custom Rules: Enforce unique application-specific rules (e.g.,
usernames must be unique).
Validating form data in React
• Common Validation Rules
• Required Fields: Ensure the user doesn't leave a field empty.
• Format Validation: Check specific patterns (e.g., email,
phone numbers).
• Length Validation: Ensure input meets length requirements
(e.g., password length).
• Range Validation: For numeric or date inputs, validate
min/max limits.
• Custom Rules: Enforce unique application-specific rules (e.g.,
usernames must be unique).
Validating form data in React
• Simple Validation Workflow
1.User types data into the form.
2.On each change or blur event:
1.Validate the input.
2.Update the state for errors and values.
3.On form submission:
1.Validate all fields.
2.If valid, submit the data to the server.
3.If invalid, prevent submission and show errors.
Validating form(controlled) data in React(email)
//email validation
import React, { useState } from 'react';
export default function ValidatedForm() {
const [email, setEmail] = useState('');
const [error, setError] = useState('');

const handleChange = (e) => {


const value = e.target.value;
setEmail(value);

// Simple validation
if (!/\S+@\S+\.\S+/.test(value)) {
setError('Invalid email address');
} else {
setError('');
}
};
const handleSubmit = (e) => {
e.preventDefault();
if (!error) {
alert('Email submitted successfully....');
}
};

return (
<form onSubmit={handleSubmit}>
<label>
Email:
<input type="email" value={email} onChange={handleChange} />
</label>
{error && <p style={{ color: 'red' }}>{error}</p>}
<button type="submit" disabled={!!error}>
Submit
</button>
</form>
);
}
Validating form data in React(output)
Example for Uncontrolled Form
import React, { useRef } from "react";

const UncontrolledForm = () => {


// Refs to access input values
const nameInputRef = useRef(null);
const emailInputRef = useRef(null);

const handleSubmit = (event) => {


event.preventDefault(); // Prevent form refresh

// Access input values using refs


const enteredName = nameInputRef.current.value;
const enteredEmail = emailInputRef.current.value;

// Log or process the form data


console.log("Name:", enteredName);
console.log("Email:", enteredEmail);

// Optionally clear the inputs


nameInputRef.current.value = "";
emailInputRef.current.value = "";
};
return (
<div>
<h1>Uncontrolled Form Example</h1>
<form onSubmit={handleSubmit}>
<div>
<label htmlFor="name">Name:</label>
<input type="text" id="name" ref={nameInputRef} />
</div>
<div>
<label htmlFor="email">Email:</label>
<input type="email" id="email" ref={emailInputRef} />
</div>
<button type="submit">Submit</button>
</form>
</div>
);
};
export default UncontrolledForm;
Integrating third-party libraries with React
• Sending form data in JSON format to a remote API

• Building some new kinds of components, including a location picker,


typeahead, and a display map

• Integrating your React app with Mapbox to search locations and


display maps
• npm install
Routing in React (React Router)
• Routing is a process in which a user is directed to different pages based on their action
or request. ReactJS Router is mainly used for developing Single Page Web
Applications.

• React Router is used to define multiple routes in the application. When a user types
a specific URL into the browser, and if this URL path matches any 'route' inside the router
file, the user will be redirected to that particular route.

• React Router is a standard library system built on top of the React and used to create
routing in the React application using React Router Package. It provides the synchronous
URL on the browser with data that will be displayed on the web page. It maintains the
standard structure and behavior of the application and mainly used for developing single
page web applications.

• Need of React Router

• React Router plays an important role to display multiple views in a single page
application. Without React Router, it is not possible to display multiple views in React
applications. Most of the social media websites like Facebook, Instagram uses
React Router for rendering multiple views.
Routing in React (React Router installation)
• React contains three different packages for routing.

1.react-router: It provides the core routing components and functions for the
React Router applications.
2.react-router-native: It is used for mobile applications.
3.react-router-dom: It is used for web applications design.
It is not possible to install react-router directly in your application. To use react
routing, first, you need to install react-router-dom modules in your application. The
below command is used to install react router dom.

$ npm install react-router-dom --save


• Components in React Router
• There are two types of router components:
• <BrowserRouter>: It is used for handling the dynamic URL.
• <HashRouter>: It is used for handling the static request.
Routing in React (App.js)
import React from 'react';
import { BrowserRouter as Router, Routes, Route, Link } from 'react-router-dom';
import Home from './Home';
import About from './About';
import Contact from './Contact';

const App = () => {


return (
<Router>
<div>
<h1>React Router Demo</h1>
{/* Navigation Bar */}
<nav>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/about">About</Link></li>
<li><Link to="/contact">Contact</Link></li>
</ul>
</nav>
Routing in React (App.js)
{/* Routes for Pages */}
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/contact" element={<Contact />} />
</Routes>
</div>
</Router>
);
};

export default App;


Routing in React (Home.js)
import React from 'react';
const Home = () => {
return (
<div>
<h2>Home Page</h2>
<p>Welcome to the home page!</p>
</div>
);
};
export default Home;
Routing in React (About.js)
import React from 'react';
const About = () => {
return (
<div>
<h2>About Page</h2>
<p>This page provides information about us.</p>
</div>
);
};
export default About;
Routing in React (Contact.js)
import React from 'react';
const Contact = () => {
return (
<div>
<h2>Contact Page</h2>
<p>Feel free to contact us at [email protected].</p>
</div>
);
};
export default Contact;
Routing in React (Output)
MEAN
S.NO AND
MEAN MERN
Stack FULL STACK MERN Stack

It’s technology stack comprises of It’s technology stack comprises of


1
MongoDB, Angular, Express and Node. MongoDB, React, Express and Node.

2 It is a javascript framework. It is open source JS library.

3 It uses Typescript language. It uses JavaScript, JSX.

4 It offers better productivity. Its offers low productivity.

5 Its learning curve is steep. It offers far better documentation.

It helps in managing and rendering the


6 It facilitates smooth rendering.
code.

7 It’s flow of data is bidirectional. It’s flow of data is unidirectional.

8 It does not support mobile application. It supports mobile application.

9 Google-October 2010 Facebook Community-March 2013


S.NO ReactJS React Native
MEANThe
AND MERN FULL STACK
ReactJS initial release was in 2013. The React Native initial release was in 2015.
1

2 It is used for developing web applications. It is used for developing mobile applications.

3 It uses a JavaScript library and CSS for It comes with built-in animation libraries.
animations.
It has built-in Navigator library for navigating
4 It uses React-router for navigating web pages.
mobile
applications.
It uses HTML tags. It does not use HTML tags.
5

It can use code components, which It can reuse React Native UI components &
6
saves a lot of valuable time. modules which allow hybrid apps to render natively.

In this, Native uses its API to render code for


7 In this, the Virtual DOM renders the browser
mobile applications.
code.

You might also like