DEV Community

Nikhil Soni
Nikhil Soni

Posted on

Passing data from React Router's Link to another component.

Hey everyone,
In this article, let us understand how to pass data from one route to another route.

Suppose we have a user list on the home page, all users are listed as User components.We need to go to the ViewUser component to see the detail of the user on which we clicked.

How we will implement this ?

There may be different approaches, but I will focus on approach in which data will be passed from one route to another route.
To do this with React Router, we can pass data from one Link to new Route that is being rendered.

Let's take an example to understand this approach more clearly.

const Home = () => {
  const userList = [
    {
      id: 1,
      name: 'ajay',
      age: 25,
      country: 'India',
    },
    {
      id: 2,
      name: 'john',
      age: 35,
      country: 'US',
    },
    {
      id: 3,
      name: 'kamal',
      age: 25,
      country: 'UK',
    },
  ];
  return (
    <div>
      {userList.map((user) => {
        return <User user={user}></User>;
      })}
    </div>
  );
};

Enter fullscreen mode Exit fullscreen mode
const User = (props) => {
  const { name, id } = props.user;
  return (
    <Link to={`/user/${id}`} state={props.user}>
      <div>
        <p>Name: {name}</p>
        <p>User id: {id}</p>
      </div>
    </Link>
  );
};
Enter fullscreen mode Exit fullscreen mode

In the above example, there are two components, in Home components all users are listed and another is the User component which is using Link to go to another route.

When the user clicks on the user component it will navigate to the ViewUser component.

const ViewUser = () => {
  const location = useLocation();
  const user = location.state;
  return (
    <div>
      <p>Name: {user.name}</p>
      <p>Age: {user.age}</p>
      <p>Country: {user.country}</p>
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

As mentioned in the above ViewUser component we need user's other details name, age, country.

So how we will pass this information to ViewUser Component from User Component.

To do this, we have to include a state prop with the data we want to pass along - in our case, it is user data.

<Link to={`/user/${id}`} state={props.user}>
      <div>
        <p>Name: {name}</p>
        <p>User id: {id}</p>
      </div>
    </Link>
Enter fullscreen mode Exit fullscreen mode

So how do we get access to the data on state in ViewUser? When we pass data along via the state property that will be available on the location's state property, which we can get using React Router's custom hook.

const location = useLocation();
const user = location.state;
Enter fullscreen mode Exit fullscreen mode

Top comments (0)