• Angular
  • React
  • NextJs
  • Sass

How to Pass and Access Data From One Route to Another in the ReactJs

By Webrecto, October 24, 2023

In this article, we will learn how many types of ways to send data from one route to another route. The latest version of react-router-dom provides many hooks to transfer and access data from one component to another component without creating parent-to-child relations.

How to Pass and Access Data From One Route to Another in the ReactJs

The react-router-dom version 6 is a perfect library to pass and access the props data in the React application. The React Router provides many hooks like useNavigate, useLocation, and useParams these permit to you pass and access data from one route to another route in between components. The Link component and useNavigate function are used to send the object data when we use the click tab or button.

With the help of react-router hooks, we can send data very easily to multiple components without making any relation between these components. In the latest version of React Router, the useLocation and useParams hooks are used to retrieve the data in pages.

Syntax

Pass Data From Link component

<Link to="/employee" state={{ state: 
      { name: "Shobhit", city: "Noida", compName: "WebRecto" }
}}>Employee</Link>

Pass Data From UseNavigate hook

navigate("/employee", navigate("/customerlist", 
      { state: { name: "Shubham", age: 35, city: "Delhi", Mob: 123456789 }}
);

Pass Data From the URL Parameters

<Link to="/employee/:name">Employee</Link>

Access Data from useLocation hook

const location = useLocation();
const data = location.state;

Access Data from useParams hook

const params = useParams();
<div>{params.name}</div>

Note: The useHistory() hook has been deprecated in the react-router dom v6

Link component: The Link component is imported from the react-router-dom library. It is used to navigate a different route. It is the same type of HTML anchor tag. We can pass data from the Link component as a prop.

useNavigate() hook: The useNavigate() hook returns a function and it is also used to navigate a different route and pass data as a prop. The useNavigate() is totally different from the Link component, it can be used conditionally in react code.

useLocation() hook: The useLocation() hook returns the current URL. In the application, if the URL changes, the useLocation will be updated as well. The useLocation() is a replacement for useHistory().

useParams() hook: The useParams() hook is to get the parameter from the route. The useParams is used to access data from the current route.

Step 1: Pass the Data from Link Component

App.js

import React from 'react';
import './App.css';
import { BrowserRouter as Router, Route, Link, Routes, useNavigate} from "react-router-dom";
import Dashboard from "./Dashboard";
import Employee from "./Employee";
import Customer from "./Customer";
import CustomerList from "./Customer/CustomerList";
import UserInfo from "./UserInfo";

function App(props) {
  return (
   <div className="App">
      <h2>Pass and Access Data From One Route to Another::webrecto.com</h2>
      <Router>
        <div>
          <nav>
            <ul>
              <li><Link to="/">Dashboard</Link></li>
              <li><Link to="/employee" state={{ state: { name: "Shobhit", city: "Noida", compName: "WebRecto" }}}>Employee</Link></li>
              <li><Link to="/customer">Customer</Link></li>
            </ul>
          </nav>
          <Routes>
            <Route path="/" element={<Dashboard />} />
            <Route path="/employee" element={<Employee />} />
            <Route path="/customer" element={<Customer />} />
            <Route path="/customerlist" element={<CustomerList />} />
            <Route path="/userinfo/:username" element={<UserInfo />} />
          </Routes>
        </div>
      </Router>
    </div>
  );
}

export default App;

Access the Data From the useLocation hook on the Employee Page

Employee.js

import React, {useState} from 'react';
import { useLocation } from "react-router-dom";

const Employee = () => {
  const location = useLocation();
  const data = location.state.state;
  return (
   <div>
      <p><b>Employee Name:</b></p>
      <p>Name: {data.name}</p>
      <p>City: {data.city}</p>
      <p>Company: {data.compName}</p>
    </div>
  );
};
export default Employee;

In the above example, I created an App.js component in my dummy project. I configured the React router to link more than one component to open different routes. I am using state prop in the employee route. The state prop contains a user object and passes some information from App.js to the Employee page.

The Employee component uses the useLocation() hook to get the user object from the state prop. When the render Link component from App.js, the user info will updated on the employee page. We can display the user information on the employee page with the help of the useLocation hook.

Output

Employee Name:
Name: Shobhit
City: Noida
Company: WebRecto

Step 2: Pass the Data from useNavigate hook

In this example, we will pass the customer data from the customer page to the customer list using the useNvigate hook.

Customer.js

import React from 'react';
import { useNavigate } from "react-router-dom";

const Customer = () => {
  const navigate = useNavigate();
  const customerListBtn=()=>{
    navigate("/customerlist", { state: { name: "Shubham", age: 35, city: "Delhi", mob: 123456789 }})
  }
  return (
   <div>
      <h3>Customer Name</h3>
      <button className="btn" onClick={()=>customerListBtn()}>Go to Customer List</button>
    </div>
  );
};
export default Customer;

Access the Data From the useLocation hook on the CustomerList Page

CustomerList.js

import React from 'react';
import { useLocation } from "react-router-dom";

const CustomerList = () => {
    const location = useLocation();
    const data = location.state;
  return (
   <div>
      <h3><b>Customer Name:</b></h3>
      <p>Name: {data.name}</p>
      <p>Age: {data.age}</p>
      <p>City: {data.city}</p>
      <p>Mobile: {data.mob}</p>
    </div>
  );
};
export default CustomerList;

In the above example, We are passing customer information from one page to another page through a button click. The Customer page adds renders a button and has click event handler. The navigate method is invoked from the customerListBtn() click event. When the user calls the button the navigate() method passes the customer data from a certain path.

The customerList page uses the useLocation hook to get the customer object from the state object. Now data is ready to display on the customerlist page.

Output

Customer Name:
Name: Shubham
Age: 35
City: Delhi
Mobile: 123456789

Step 3: Pass the Data Through URL Params

The URL params are one of the best ways to pass variables from the path. The variable contains static or dynamic data from the user in the application.

Dashboard.js

import React from 'react';
import { useNavigate } from "react-router-dom";
const Dashboard = () => {
  const navigate = useNavigate();
  var userDetails =[
    {id:1, name: "Radheshyam"},
    {id:2, name: "Amit"},
    {id:3, name: "Rajesh"},
  ]
  const userInfo=(name)=>{
    navigate(`/userinfo/${name}`);
  }
  return (
   <div>
      <h3>Dashboard</h3>
         <p>User List:</p>
         <ul className="user">
         {
            userDetails.map((user) => {
               return(
               <li onClick={()=> userInfo(user.name)}>{user.name}</li>
               )
            })
         }
         </ul>
    </div>
  );
};
export default Dashboard;

Access the data from useParams hook

UserInfo.js

import React from 'react';
import { useParams } from "react-router-dom";

const UserInfo = (props) => {
  const { username } = useParams();
  return (
   <h3>User Name - {username}</h3>
  );
};
export default UserInfo;

Output

Radheshyam
Amit
Rajesh

In the above example, We configure the unserInfo route in App.js and set the name variable in the URL path. I created an array data for storing the user name and itrate Array in the Dashboard.js component to display the name. All user contains the click event method. The navigate method is wrapped from the userInfo method. The navigate methods call the userinfo path with a param variable. In the param variable set the user name when calling the click event.

Conclusion

We all learned about a new feature of the latest react-router-dom. This is the best practice for sending and getting data from one page to another page with the help of the provided inbuild method. As per our understanding, the useNavigate and useLocation function is very easy to use in the application.

Find the print screen of the output.

How to Pass and Access Data From One Route to Another in the ReactJs

Reference

Download Source Code