Open In App

Passing Data via Link Component using BrowserRouter in React

Last Updated : 11 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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;

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;

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:

Screenshot-2024-03-08-111506

Project Structure

Example: 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 :
Screenshot-2024-03-02-234232



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads