Home > database >  How to handle dynamic routes with HashRouter in React?
How to handle dynamic routes with HashRouter in React?

Time:01-20

I'm working with a hashrouter and I want to support dynamic path (ie: /user/:id).

The way I've done it is :

<HashRouter>
    <Routes>
        <Route index element={<App />} />
        <Route path="/user/:id" component={User}/>
    </Routes>
</HashRouter>

I also tried working with render:

<Route path="/user/:id" render={(props) => <User {...props} />}/>

But nothing seem to work.

What is the proper way to do this ?

CodePudding user response:

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 />} />
  •  Tags:  
  • Related