Hey! To implement dynamic routing in React using React Router, you can use the useParams hook to capture the dynamic part of the URL. Here's how you can set it up:
-
Install React Router (if you haven't already):
npm install react-router-dom - Set up your routes in
App.js(or wherever you're managing your routes). To create a dynamic route, use a colon (:) followed by the dynamic segment name, like:userIdor:productId.import { BrowserRouter as Router, Route, Routes } from 'react-router-dom'; import UserPage from './UserPage'; function App() { return ( <Router> <Routes> <Route path="/user/:userId" element={<UserPage />} /> </Routes> </Router> ); } export default App; - Access the dynamic parameter using the
useParamshook inside your component (in this case,UserPage). This hook will give you access to theuserIdfrom the URL.import { useParams } from 'react-router-dom'; function UserPage() { const { userId } = useParams(); // Extracting userId from the route return ( <div> <h1>User ID: {userId}</h1> </div> ); } export default UserPage;
In the example above, if you visit /user/123, it will display "User ID: 123". The useParams hook makes it really simple to access the dynamic part of the URL.
Let me know if you need any more details!