DEV Community

Cover image for Passing Data (states) through React Router
thatFemicode
thatFemicode

Posted on

Passing Data (states) through React Router

Introduction

I was working on a side project recently in React and i wanted to pass data(state) from a component (Page) that was not in my initial component to another component(page). This might sound confusing but let me explain, basically the component i wanted to pass this particular state to was not imported to my component because it was a stand alone page i.e. had a different route, this was giving me issues for about a day till i started going through the react router docs and found out that you can pass state with Link component and useNavigate hook from react-router-dom routing package for react.
This article shows you a elegant approach to passing data via the Link component and useNavigate hook and accessing the data passed with the useLocation hook which is just a simple technique. I will display code using React functional components. Without further ado, let's get into it.

Passing Data

Data known as state can be passes via the Link component in the same way we pass props but it has a certain key (name) that has to be given to it in order for the data to be retrieved via the useLocation hook and also with the useNavigate hook also to be retrieved via the useLocation hook.

I'll be explaining both methods and how they can be done.

Link

import { Link } from 'react-router-dom';
const item = () =>{
//data to be passed
const Data = {
  name: 'Femi',
  phoneNumber: 123
}
<Link to="/some-where" state={myData}>Link Text</Link>
}
Enter fullscreen mode Exit fullscreen mode

the above shows the Item (Route) component that we passed the data from, we will be retrieving the data below in Profile (Route) component.

useNavigate

import { useNavigate } from 'react-router-dom';
const item = () =>{
  const nav = useNavigate();
//data to be passed
const Data = {
  name: 'Femi',
  phoneNumber: 123
}
<div onClick={() => {
 nav("/some-where", { state:data});
}}>Clickme
</div>
}
Enter fullscreen mode Exit fullscreen mode

The below shows how data is retreived after it has been passed by the two methods above.

import { useLocation } from 'react-router-dom';
const Profile = () =>{
const location = useLocation();
//the data here will be an object since an object was
const data = location.state;
console.log(data);
<p>data.name</p>
<p>data.phoneNumber</p>
}
Enter fullscreen mode Exit fullscreen mode

Illustrating the above in a simple project

I'm guessing most of us can set up a react project with the traditional npx-create-react-app appname method, if you dont kindly check on how to do this from the react docs.

I will be using just the Link component to shocase this little build
Three Major component here.

  • App.jsx
  • Home.jsx
  • Profile.jsx

//App.jsx

import React from "react";

// import things from react-router-dom
import { BrowserRouter, Routes, Route } from "react-router-dom";

// import pages
import HomePage from "./Home";
import ProfilePage from "./Profile";
function App() {
  return (
<BrowserRouter>
  <div style={{padding: 30}}>
    <Routes>
 <Route path="/" element={<HomePage/>} /><Route path="/about" element={<ProfilePage />} />
   </Routes>
 /div>
 </BrowserRouter>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

//Home.jsx

import { Link } from "react-router-dom";

const HomePage = () => {
  // this is for the first Link
  const data1 = {
    from: "David",
    message: "Welcome to David.com",
    return (
    <>
      <h1>Home Page</h1>
      <p>
        <Link to="/about" state={data1}>
          Go to Profile Page
        </Link>
      </p>
    </>
  );
};

Enter fullscreen mode Exit fullscreen mode

//Profile.jsx

import { useLocation, Link } from "react-router-dom";

const Profile = () => {
  const location = useLocation();
  const state = location.state;
  console.log(state);
  return (
    <>
<h1>Profile page</h1>  
   <div>
      <h3>Passed data:</h3>
       <p>From: {state.from}</p>
       <p>Message: {state.message}</p>
       <p>Timestamp: {state.timestamp}</p>
    </div>
      <Link to="/">Go Home</Link>
    </>
  );
};
Enter fullscreen mode Exit fullscreen mode

Conclusion

You can now pass data with Link components or useNavigate hook from react-router-dom package provided you use the useLocation to get access to the passed data. If you feel i made a mistake, kindly hit me to tell me what i missed, thanks for reading.

Top comments (3)

Collapse
 
katyi profile image
Alexandra Egorova

Thanks, it was helpful for me )))

Collapse
 
ak274 profile image
Ankush Kalia

What if you directly want to reach to that link or share that link with others so that they can click on it in that case state will be lost.

Collapse
 
bishalkar10 profile image
Gain Prasad Kar

This is much simpler. use context and redux is much more complex.....