Passing and Using URL Parameters in React Router
1. Define a Route with a Parameter
import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
import UserProfile from "./UserProfile";
const App = () => {
return (
<Router>
<Routes>
<Route path="/user/:id" element={<UserProfile />} />
</Routes>
</Router>
);
};
export default App;
2. Access the Parameter in the Component
import { useParams } from "react-router-dom";
const UserProfile = () => {
const { id } = useParams(); // Extracts 'id' from the URL
return <h1>User ID: {id}</h1>;
};
export default UserProfile;
3. Navigate with a Dynamic URL
import { Link } from "react-router-dom";
<Link to="/user/123">Go to User 123</Link>