amann amann - 1 year ago 162
React JSX Question

Programmatic relative links with react-router

Did somebody manage to find a good way how to programmatically navigate to a relative link with react-router?

I've used react-router-relative-links for declarative links, but I can't find a good way to do this programmatically.

I know it could be done manually with resolve-pathname and

, but that would require access to the
, which is only available on route handler components. My component is somewhat deep down the tree, therefore I'd like to avoid all the wiring back to the top.

the right way to get the location and then use
available through

Currently I'm using this as a utility function:

import resolvePathname from 'resolve-pathname';

function getPathnameFromRelativeLocation(relativeLocation) {
let {pathname} = window.location;
let basePath = pathname.endsWith('/') ? pathname : pathname + '/';
return resolvePathname(relativeLocation, basePath);

And in an event handler of a React component:

// Current path is `/books/123`
let path = getPathnameFromRelativeLocation('write-review');
// Current path is `/books/123/write-review`

Answer Source

react-router 3.0 now provides location on the context so it's now easy to just take it from there.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download