If you have a route such as:
<Route path="/users/:userId" />
And then you export that route, and so it can be used across your app, such as:
export const MY_ROUTE = '/users/:userId/';
<Route path={MY_ROUTE} />
How do you set the param in a link dynamically? i.e. I would like to do this:
<Link to={MY_ROUTE} params={{userId: 1}} />
but params is totally ignored... and query just makes a query (?userId=) not a param... any ideas?
Taken from React Router official docs:
From the upgrade guide from 1.x to 2.x:
<Link to>
, onEnter, and isActive use location descriptors
<Link to>
can now take a location descriptor in addition to strings. The query and state props are deprecated.// v1.0.x
<Link to="/foo" query={{ the: 'query' }}/>
// v2.0.0
<Link to={{ pathname: '/foo', query: { the: 'query' } }}/>
Unfortunately, there's no support for passing in a param
object, you yourself saw that.
In order to dynamically use the route you proposed, you would have to do something along the lines of:
<Link to={ MY_ROUTE.replace(':userId', '<someUserIdFromSomewhere>') }/>
Or you could further optimize by instead of exporting a string for MY_ROUTE
, you could export a userLink
function as such:
function userLink(userId) {
return `/users/${userId}/`;
}
and then use that wherever you would want to use a Link
to the route.
Below you can find supported parameters and API exposed on the Link
component:
Router Link API
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With