Passing Data via Link Component using BrowserRouter in React
Last Updated :
24 Apr, 2025
It is common for React apps to need data to be passed across components as they are navigated. A well-liked library for managing routing in React apps is called React Router DOM. It offers a method for switching between various React application components and pages while maintaining synchronization between the user interface and the URL.
The <Link> Component in React Router is mainly used for navigation, but it may also be effectively utilized to transfer data between components. Here is step-by-step guidance on how to use Link tag and pass data along with it.
Understanding React Router:
To begin passing data via links in React applications, one must first install React Router, a widely used library for managing navigation. It facilitates the definition of routes and associated components to render when specific URLs are accessed.
Syntax to Import React Router
npm install react-router-dom
Setting Up Routes:
To enable data passing through links, the initial step involves configuring routes within our application. This typically involves importing necessary modules and defining routes using the Route
component provided by React Router in the main component, often named App.js
.
import React from 'react';
import {
BrowserRouter as Router,
Route,
Link
} from 'react-router-dom';
import Home from './components/Home';
import OtherComponent from './components/OtherComponent';
function MyCustomApp() {
return (
<Router>
<Link to="/other">Go to Other Component</Link>
<Route exact path="/" component={Home} />
<Route path="/other" component={OtherComponent} />
</Router>
);
}
export default MyCustomApp;
Passing Data Via Links:
With React Router, the passage of data alongside links involves utilizing the to
prop within the Link
component. This to
prop accepts an object comprising the pathname and a state object carrying the desired data for transmission.
import React from 'react';
import { Link } from 'react-router-dom';
function Home() {
const dataToPass = { name: 'GeeksforGeeks', age: 20 };
return (
<div>
<h1>Welcome to the Home Component</h1>
<Link to={{
pathname: '/other',
state: dataToPass
}}>
Go to GeeksforGeeks Page
</Link>
</div>
);
}
export default Home;
Receiving Data in the Destination Component:
Accessing the transmitted data from the link involves utilizing the location
prop within the destination component. Within this prop, the data becomes accessible through the state
object.
import React from 'react';
function OtherComponent(props) {
const { state } = props.location;
const { name, age } = state;
return (
<div>
<h1>Hello GeeksforGeeks pages</h1>
<p>Name: {name}</p>
<p>Age: {age}</p>
</div>
);
}
export default OtherComponent;
Steps to Implement Link Component to Pass Data in React :
Step 1: Create a React application using the following command.
npx create-react-app my-react-app
Step 2: Naviage to the root directory of your application using the following command.
cd my-react-app
Project Structure:
Project StructureExample: Below is an example of passing data with Link using BrowseRouter.
CSS
.cardDesign {
margin: 100px;
display: flex;
justify-content: flex-end;
}
.mainDivision {
display: grid;
grid-template-columns: 5fr 5fr;
}
.navigation_class {
margin: 20px;
}
CSS
.checkOutButton {
margin: 20px;
}
JavaScript
// App.js
import './App.css';
import Cart from './Cart';
import Home from './Home';
import BookItem from './BookItem';
import {
BrowserRouter,
Route,
Routes
} from 'react-router-dom';
function App() {
const items = [new BookItem('Wealth wont wait',
'mike desormeaux', 2023, 230, 34.4),
new BookItem('The Zen Monkey and the lotus flower',
'Tenpa Yeshe', 2020, 150, 50),
new BookItem('', 'mike desormeaux',
2018, 100, 23),
new BookItem('The Family across the street',
'nicole trope', 2023, 434, 23.4),
new BookItem('The psychology of money',
'Morgan Housel', 2012, 1000, 50),
new BookItem('Atomic Habits',
'James clear', 2017, 135, 64.34),
new BookItem('Cant hurt me',
'David Goggins', 2021, 433, 63.3),
new BookItem('The four agreements',
'Don Miguel Ruiz', 2000, 343, 64.63)];
const cart = []
const addToCart = (index) => {
cart.push(items[index])//where i is index;
alert(index + ' index element added ')
}
const clearCart = () => {
cart.length = 0;
/*
clearing all elements from a list in js
*/
//alert('cart cleared')
}
const checkCartItem = () => {
alert('items in cart are ' + cart.length)
}
return (
<div>
<BrowserRouter>
<Routes>
<Route index element={
<Home items={items}
onHandleAddToCart={addToCart}
onHandleCheckCartItem={checkCartItem}
onHandleClearCart={clearCart} />} />
<Route path='/cart' element={
<Cart selectedProducts={cart} />} />
</Routes>
</BrowserRouter>
</div>
);
}
export default App;
JavaScript
// Home.js
import React from "react";
import {
Component,
Fragment
} from "react"
import BookItem from "./BookItem"
import './Home.css'
import 'bootstrap/dist/css/bootstrap.css';
import {
Card,
CardHeader,
CardTitle,
Button,
CardFooter,
CardBody,
CardText
} from "reactstrap";
import {
Nav,
NavItem,
NavLink
} from "reactstrap";
import { Link } from "react-router-dom";
import Cart from './Cart';
const Home = ({ items, onHandleAddToCart,
onHandleCheckCartItem, clearCart }) => {
return (
<Fragment>
<div class='navigation_class'>
<Nav
card
justified
pills
>
<NavItem>
<NavLink href='/'>
Home
</NavLink>
</NavItem>
<NavItem>
<Link to='/cart'>
Cart
</Link>
</NavItem>
<NavItem>
<NavLink
onClick={() => onHandleCheckCartItem}>
Check Cart
</NavLink>
</NavItem>
</Nav>
</div>
<div>
{
//mapping a item in js
items.map((currentItem, index) => {
//alert('loop executed '+index)
return (
<Fragment>
<Card
className="my-2"
style={{
width: '97%',
margin: '20px'
}}
>
<CardHeader>
{currentItem.getName()}
</CardHeader>
<CardBody>
<CardTitle tag="h5">
{currentItem.getAuthor()}
</CardTitle>
<CardText>
Price : {currentItem.getPrice()}
</CardText>
<Button
onClick={() => onHandleAddToCart(index)}>
Add to Cart
</Button>
</CardBody>
<CardFooter>
</CardFooter>
</Card>
</Fragment>
)
})}
</div>
</Fragment>
)
}
export default Home;
JavaScript
import { Component } from "react";
import { Fragment } from "react";
import {
Card,
CardHeader,
CardBody,
CardTitle,
CardText,
CardFooter,
Button
} from "reactstrap";
import './Cart.css'
export default class Cart extends Component {
constructor(props) {
super(props)
this.state = { props }
console.log("The product received is " +
this.state.selectedProducts);
props.selectedProducts.map((currentItem,
index) => {
console.log(currentItem.getName());
})
}
render() {
return (
<Fragment>
<div>
{
this.props.selectedProducts.map(
(currentItem, index) => {
return (
<Fragment>
<Card
className="my-2"
style={{
width: '97%',
margin: '20px'
}}
>
<CardHeader>
{currentItem.getName()}
</CardHeader>
<CardBody>
<CardTitle tag="h5">
{currentItem.getAuthor()}
</CardTitle>
<CardText>
Price : {currentItem.getPrice()}
</CardText>
</CardBody>
<CardFooter>
</CardFooter>
</Card>
</Fragment>
)
})}
</div>
<div class="checkOutButton">
<Button>Check Out</Button>
</div>
</Fragment>
)
}
}
JavaScript
export default class BookItem {
constructor(bookname,
bookauthor,
YOP, pages,
price) {
this.name = bookname
this.author = bookauthor
this.yearOfPublication = YOP
this.pageCount = pages
this.bookPrice = price
}
setName(itemName) {
this.name = itemName;
}
getName() {
return this.name
}
setAuthor(authorName) {
this.author = authorName;
}
getAuthor() {
return this.author
}
setYear(yop) {
this.yearOfPublication = yop;
}
getYear() {
return this.yearOfPublication
}
setPages(count) {
this.pageCount = count;
}
getCount() {
return this.pageCount
}
setPrice(itemValue) {
this.price = itemValue;
}
getPrice() {
return this.price
}
}
Output :

Similar Reads
How to Create Breadcrumb Component in React with Plain CSS ?
In ReactJS, we can create a Breadcrumb Component easily with Plain CSS. We have to make a new component with JSX code to get a basic HTML code for the Breadcrumb, and then we have to apply CSS effects to make some changes and make its appearance the best. Prerequisites:NodeJS or NPMReact JSCSSApproa
2 min read
Link and NavLink components in React-Router-Dom
When creating a React app, handling navigation properly is important. React Router provides two key components, Link and NavLink, to make moving between pages easy. These components work like regular <a> tags but prevent full-page reloads, making the app faster and smoother for users.What is a
4 min read
Explain the Purpose of the BrowserRouter and Route Components
React Router provides a powerful library for handling dynamic routing within React applications, enabling client-side navigation without reloading the entire page. Two of the most important components in React Router are BrowserRouter and Route. What is BrowserRouter?BrowserRouter is a special compo
5 min read
How to Pass Data from One Component to Another Component in ReactJS?
In ReactJS, components are the building blocks of your user interface. Components allow you to create modular, reusable UI elements, but sometimes these components need to communicate with each other.In this article, we will explore the different methods to pass data between components in ReactJS.1.
5 min read
Create Web Browser using React-Native
In this article, we will build the Web Browser using the React Native language. In this application, there will be as search bar with the button. The uer can enter the search text or the URL and click on the button, the browser will take to the desired result. Also there are morre naivtional buttons
7 min read
Difference between Link and Navigate Component in React Router
In this article, we'll delve into the intricacies of two fundamental components within the widely acclaimed React Router Dom Library a Link and Navigate. As the backbone of many react applications, these components play pivotal roles in facilitating seamless navigation and routing. We'll explore the
4 min read
React-Bootstrap Pagination Component
React-Bootstrap is a front-end framework that was designed keeping react in mind. Pagination Component provides a way for users to switch between pages easily. It is basically a set of presentational components for providing a better UI experience to the user. We can use the following approach in Re
2 min read
React.js Blueprint Panel stack (v2) Component Panels
Blueprint is a React-based UI toolkit for the web. This library is very optimized and popular for building interfaces that are complex and data-dense for desktop applications. In this article, we'll discuss React.js Blueprint Panel stack (v2) Â Component Panels. The panel stack(v2) is used in managin
5 min read
How to Send state/props to Another Component in React with onClick?
The props and state are the main concepts of React. Actually, only changes in props and/ or state trigger React to re-render your components and potentially update the DOM in the browserProps are used to pass data from a parent to a child component.State is used to manage dynamic data within a compo
3 min read
ReactJS UI Ant Design Breadcrumb Component
Ant Design Library has this component pre-built, and it is very easy to integrate as well. Breadcrumb Component provides a way to indicate the location of the current page. We can use the following approach in ReactJS to use the Ant Design Breadcrumb Component. Syntax: <Breadcrumb> <Breadcr
2 min read