Using useParams Hook
Introduce the `useParams` hook to access the dynamic parameters of a route within components, making it easy to extract and use route information.
import { useParams } from 'react-router-dom';
function UserProfile() {
// The useParams hook allows us to access the URL parameters from the current route.
const params = useParams();
// For example, if the route is '/user/:userId', params will contain { userId: '...' }.
console.log(params);
// You could then use params.userId to fetch user data or perform other actions.
return (
<div>
<h1>User Profile</h1>
<p>User ID: {params.userId}</p>
// Render additional user information here...
</div>
);
}
export default UserProfile;
In this piece of code, we are importing the useParams hook from 'react-router-dom'. Then, we are using it within the `UserProfile` functional component to extract the URL parameters. For example, if the app navigates to a URL that matches the pattern '/user/:userId', the useParams hook will provide an object containing the 'userId' parameter, which is then used to display the user's profile.