The useParams hook is part of React Router and is used to access the dynamic parameters from the current URL. This hook is primarily useful when you have routes with dynamic segments, such as user IDs, product IDs, or other variable data that is embedded in the route path.
For example, if you are building a blog and want to display a specific post based on its ID, you would use useParams to fetch the post ID from the URL and display the corresponding post.
const params = useParams();
Let’s say you have a route for displaying a user profile, where the route is /profile/:userId, and :userId is a dynamic segment.
import React from 'react'; import { BrowserRouter as Router, Route, Routes } from 'react-router-dom'; import UserProfile from './UserProfile'; const App = () => { return ( <Router> <Routes> <Route path="/profile/:userId" element={<UserProfile />} /> </Routes> </Router> ); }; export default App;
import React from 'react'; import { useParams } from 'react-router-dom'; const UserProfile = () => { const { userId } = useParams(); // Extracts the userId from the URL return ( <div> <h2>User Profile</h2> <p>Displaying details for user with ID: {userId}</p> </div> ); }; export default UserProfile;
You can have multiple dynamic parameters in the route, and useParams will return all of them.
import React from 'react'; import { BrowserRouter as Router, Route, Routes } from 'react-router-dom'; import PostDetail from './PostDetail'; const App = () => { return ( <Router> <Routes> <Route path="/post/:postId/comment/:commentId" element={<PostDetail />} /> </Routes> </Router> ); }; export default App;
import React from 'react'; import { useParams } from 'react-router-dom'; const PostDetail = () => { const { postId, commentId } = useParams(); // Extracts postId and commentId from the URL return ( <div> <h2>Post Details</h2> <p>Post ID: {postId}</p> <p>Comment ID: {commentId}</p> </div> ); }; export default PostDetail;
You can also handle optional parameters by defining a route with a parameter that can be optionally included.
const params = useParams();
import React from 'react'; import { BrowserRouter as Router, Route, Routes } from 'react-router-dom'; import UserProfile from './UserProfile'; const App = () => { return ( <Router> <Routes> <Route path="/profile/:userId" element={<UserProfile />} /> </Routes> </Router> ); }; export default App;
The useParams hook is a simple and effective way to access dynamic parameters from the URL in your React components. It makes working with dynamic routes much easier and enables you to build more flexible and dynamic applications.
The above is the detailed content of Accessing Dynamic Route Parameters with the useParams Hook in React. For more information, please follow other related articles on the PHP Chinese website!