How to implement dynamic routing in React?
Dynamic Routing allows you to create routes that change based on the data — for example, user profiles or product pages.
Here’s how you can implement it:
- Define dynamic routes using
:param
syntax:
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom'; import UserProfile from './UserProfile'; function App() { return ( <Router> <Routes> <Route path="/user/:userId" element={<UserProfile />} /> </Routes> </Router> ); }
- Access route parameters inside the component:
import { useParams } from 'react-router-dom'; function UserProfile() { const { userId } = useParams(); return <h1>Profile Page of User: {userId}</h1>; }
Key Points:
:userId
is a dynamic segment.useParams()
hook gives access to the dynamic value inside the component.- You can fetch data based on
userId
(e.g., fetch user details from an API).
Dynamic routing makes your application more scalable and flexible by using URL parameters to render content dynamically.