Using the <Link/> we have different ways to navigate between different routes in a single-page application. <Link /> component creates a hyperlink with which we can navigate to another route without reloading the page.

There are some cases, where we may need to pass the params from source to the target route. In this article we will see how to pass the params to the target route.

Using URL path, we can pass the parameters to the target route.

For example:

<Route path="/users/:userId" component={UserProfile} />

In the above example, the :userId parameter is defined in the URL path. This parameter can be used to pass a user ID to the UserProfile component.

To navigate to this route and pass the userId parameter, we can use the <Link> component and include the parameter in the to prop as follows:

<Link to="/users/123">View User Profile</Link>

In the above example, we are passing the userId parameter with a value of 123 to the UserProfile component.

To access the userId parameter in the UserProfile component, we can use the useParams() hook provided by the react-router-dom library as shown as below.

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

function UserProfile() {
  const { userId } = useParams();

  return <div>User Profile for User {userId}</div>;

export default UserProfile;

Categorized in:

Tagged in: