amann amann - 1 month ago 14
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

router.push(…)
, but that would require access to the
location
, 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.

Is
window.location.pathname
the right way to get the location and then use
router.push
available through
withRouter
?

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');
this.props.router.push(path);
// Current path is `/books/123/write-review`

Answer

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

https://github.com/ReactTraining/react-router/issues/3325

Comments