Home > Mobile >  How can I construct a link to a "neighbour" resource in react router v6?
How can I construct a link to a "neighbour" resource in react router v6?

Time:04-24

I've got a React app using React Router v6. I've got a route matching a path with multiple path parameters, something like this:

/event/:eventId/resource/:resourceId

These are represented by nested routes, something like:

<Route path="/event/:eventId/*" element={<Event />}>
  <Route path="resource/:resourceId" element={<Resource />} />
</Route>

I have multiple events and multiple resources. A single resource might appear in the context of multiple events, corresponding to urls like this:

  • /event/event-1/resource/resource-1
  • /event/event-2/resource/resource-1

Individual resources are linked to other resources. I want to be able make links on a resource page to the other linked resources, in the context of the same event.

So on the page:

/event/event-1/resource/resource-1,

which renders my Resource component, and given that resource-1 has links to resource-2 and resource-3, I might want to make links to these urls:

  • /event/event-1/resource/resource-2
  • /event/event-1/resource/resource-3

But, I don't want to hard-code the paths for those links in my Resource component if I can avoid it.

React Router 6 allows me to create nested routes and links, so I can build up long links without having to know the full path up to that point. Does it provide a nice way to make these links without hard coding the full path?

CodePudding user response:

You can take advantage of generatePath, and/or write your own function helpers:

import { generatePath } from 'react-router-dom';

export function getResourcePath({ eventId, resourceId }) {
  return generatePath('/event/:eventId/resource/:resourceId', { eventId, resourceId });
}

In your components:

import { getResourcePath } from '...';

...

<Link to={getResourcePath(...)}/>
  • Related