Route Parameters in React Routing
Route parameters are an essential feature in React Router that enables dynamic routing. They allow you to capture specific values from the URL, making it possible to reuse components for different data. In this tutorial, we'll explore how to use route parameters in React Router, with sample code and simple explanations.
Defining Route Parameters
To define a route parameter, you need to specify a colon (:
) followed by the parameter name within the path prop of the Route
component. Here's an example:
// App.js
import React from 'react';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
import UserProfile from './UserProfile';
function App() {
return (
<BrowserRouter>
<Switch>
<Route path="/user/:userId" component={UserProfile} />
</Switch>
</BrowserRouter>
);
}
export default App;
In this example, we've defined a route parameter called userId
in the path "/user/:userId". When a user navigates to a URL like "/user/5", the UserProfile
component will be rendered with the userId
parameter set to "5".
Accessing Route Parameters
To access route parameters within a component, you can use the useParams
hook from the react-router-dom
package. Here's an example:
// UserProfile.js
import React from 'react';
import { useParams } from 'react-router-dom';
function UserProfile() {
const { userId } = useParams();
return (
<div>
<h1>User Profile</h1>
<p>User ID: {userId}</p>
</div>
);
}
export default UserProfile;
In this example, we've used the useParams
hook to extract the userId
parameter from the URL. The value of userId
can then be used to fetch user data or perform other tasks.
Conclusion
In this tutorial, we've covered the basics of route parameters in React Router. We've learned how to define route parameters, access them within a component, and use them to create dynamic routes. With this knowledge, you can build more flexible and dynamic routing structures in your React applications.
Practice using route parameters in different scenarios to become more familiar with their capabilities. As you gain experience, you'll be able to create more complex and interactive routing systems in your applications.