Skip to main content

Dynamic Routing with URL Parameters (Part 2): Accessing URL Parameters with the `useParams` Hook #94

📖 Introduction

Following our introduction to dynamic routing, this article focuses on how to access the dynamic parts of the URL in our components. We will learn how to use the useParams hook to get the URL parameters and render content accordingly.


📚 Prerequisites

Before we begin, please ensure you have a solid grasp of the following concepts:

  • All concepts from Part 1 of this series.
  • Basic React hooks.

🎯 Article Outline: What You'll Master

In this article, you will learn:

  • The useParams Hook: What it is and how it works.
  • Core Implementation: How to use the useParams hook to access URL parameters.
  • Practical Application: Building a user profile page that displays the user's ID from the URL.

🧠 Section 1: The Core Concepts of useParams

The useParams hook is a hook provided by React Router that allows you to access the URL parameters from the current route. It returns an object of key/value pairs of URL parameters.

For example, if you have a route with the path /users/:userId, and the current URL is /users/123, the useParams hook will return an object like this: { userId: '123' }.


💻 Section 2: Deep Dive - Implementation and Walkthrough

Let's update our UserProfile component to use the useParams hook.

2.1 - The UserProfile Component with useParams

// UserProfile.js
import React from 'react';
import { useParams } from 'react-router-dom';

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

return (
<div>
<h1>User Profile</h1>
<p>The ID of the user is: {userId}</p>
</div>
);
}

export default UserProfile;

Step-by-Step Code Breakdown:

  1. import { useParams } from 'react-router-dom';: We import the useParams hook from React Router.
  2. const { userId } = useParams();: We call the useParams hook and destructure the userId parameter from the returned object. The name userId must match the name of the parameter we defined in our route's path (/users/:userId).
  3. <p>The ID of the user is: {userId}</p>: We display the userId in our component.

Now, if you navigate to /users/1, the UserProfile component will render "The ID of the user is: 1". If you navigate to /users/2, it will render "The ID of the user is: 2".


🛠️ Section 3: Project-Based Example: A Simple Blog

Let's build a simple blog that has a list of posts and a page for each individual post.

3.1 - The Blog Component

// Blog.js
import React from 'react';
import { Link } from 'react-router-dom';

const posts = [
{ id: 1, title: 'My First Post' },
{ id: 2, title: 'My Second Post' },
{ id: 3, title: 'My Third Post' },
];

function Blog() {
return (
<div>
<h1>Blog</h1>
<ul>
{posts.map(post => (
<li key={post.id}>
<Link to={`/posts/${post.id}`}>{post.title}</Link>
</li>
))}
</ul>
</div>
);
}

export default Blog;

3.2 - The Post Component

// Post.js
import React from 'react';
import { useParams } from 'react-router-dom';

const posts = [
{ id: 1, title: 'My First Post', content: 'This is the content of my first post.' },
{ id: 2, title: 'My Second Post', content: 'This is the content of my second post.' },
{ id: 3, title: 'My Third Post', content: 'This is the content of my third post.' },
];

function Post() {
const { postId } = useParams();
const post = posts.find(p => p.id === parseInt(postId));

return (
<div>
<h2>{post.title}</h2>
<p>{post.content}</p>
</div>
);
}

export default Post;

3.3 - The App.js File

// App.js
import React from 'react';
import { Routes, Route } from 'react-router-dom';
import Blog from './Blog';
import Post from './Post';

function App() {
return (
<Routes>
<Route path="/blog" element={<Blog />} />
<Route path="/posts/:postId" element={<Post />} />
</Routes>
);
}

export default App;

Now, if you navigate to /blog, you will see a list of posts. Clicking on a post will take you to the corresponding post page, where the useParams hook is used to get the postId from the URL and display the correct post.


💡 Conclusion & Key Takeaways

In this article, we've learned how to use the useParams hook to access URL parameters in our components. This is a fundamental concept in building dynamic, data-driven applications with React Router.

Let's summarize the key takeaways:

  • The useParams hook returns an object of key/value pairs of URL parameters.
  • The keys in the object correspond to the dynamic segments in the route's path.
  • useParams allows us to create components that can render different content based on the URL.

Challenge Yourself: To solidify your understanding, try to add an "author" parameter to the blog post route and display the author's name on the post page.


➡️ Next Steps

You now have a solid understanding of how to use the useParams hook. In the next article, "Programmatic Navigation with useNavigate", we will learn how to navigate between routes programmatically from our code.

Thank you for your dedication. Stay curious, and happy coding!


glossary

  • useParams: A hook provided by React Router that allows you to access the URL parameters from the current route.
  • Destructuring: A JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

Further Reading