How to handle dynamic routes with HashRouter in React?
You'd still use the element
prop. All Route
components render their routed content on the element
prop as JSX, i.e. a ReactElement
.
<Route path="/user/:id" element={<User />} />
I'm guessing your next question might be, "How to access the id
route match param?"
For this use the useParams
hook in the User
component.
import { useParams } from 'react-router-dom';
...
const { id } = useParams();
If User
is a class component and can't use React hooks, then create a wrapper component that can and pass the params in as a prop.
const UserWrapper = () => {
const match = useMatch(); // i.e. match.params
return <User match={match} /> // i.e. this.props.match.params
}
...
<Route path="/user/:id" element={<UserWrapper />} />