amann
amann

Reputation: 5902

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`

Upvotes: 1

Views: 2673

Answers (2)

amann
amann

Reputation: 5902

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

Upvotes: 2

Kishore Barik
Kishore Barik

Reputation: 770

if you are using browserHistory it's simply

browserHistory.push('/yourRelativePath');

for that make sure you have latest react-router and

 import { browserHistory } from 'react-router';

Upvotes: 0

Related Questions