Welcome back! Today, we’ll explore route parameters, a powerful feature in React Router that allows you to create dynamic routes based on user input or application state. This is especially useful for displaying individual resources, such as user profiles, product details, or blog posts.
Route parameters are placeholders in the URL that allow you to capture values and pass them to your components. This enables you to create routes that can respond to dynamic data.
Let’s say we have an application where users can view their profiles. We can use route parameters to display different profiles based on the user ID in the URL.
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import UserProfile from './UserProfile';
import NotFound from './NotFound';
const App = () => {
return (
<Router>
<Routes>
<Route path="user/:id" element={<UserProfile />} />
<Route path="*" element={<NotFound />} />
</Routes>
</Router>
);
};
export default App;
- User Profile Route: The route
user/:id
captures the user ID from the URL. For example, visiting/user/123
will capture123
as the user ID. - NotFound Route: The wildcard route (
*
) is used to display a Not Found page for any other routes.
In the UserProfile
component, we can access the route parameter using the useParams
hook.
import { useParams } from 'react-router-dom';
const UserProfile = () => {
const { id } = useParams(); // Accessing the user ID from the URL
return (
<div>
<h1>User Profile</h1>
<p>Displaying profile for user ID: {id}</p>
{/* Here you could fetch user data using the ID */}
</div>
);
};
export default UserProfile;
- useParams Hook: This hook returns an object of key-value pairs of the dynamic parameters in the URL. In our case, we retrieve the
id
. - Dynamic Content: You can now use the ID to fetch and display user-specific information, making your app more dynamic and interactive.
Mia: "So, if I visit /user/456
, I’ll see the profile for user 456?"
Leo: "Exactly! This makes your routes flexible and user-friendly." 🌈
- Dynamic Content: Use route parameters when you need to display content that changes based on user input or selections.
- Resource Identification: Ideal for identifying resources, such as users, products, or articles, in a URL.
You can have multiple parameters in a single route! For example, /user/:id/post/:postId
would allow you to capture both user and post IDs.
Previous: Nested Routes: Structuring Your Application | Next: Conclusion