title: Programmatic relative links with react-router
body: <p>Did somebody manage to find a good way how to programmatically navigate to a relative link with react-router?</p>
  
  <p>I've used <a href="https://www.npmjs.com/package/react-router-relative-links" rel="nofollow">react-router-relative-links</a> for declarative links, but I can't find a good way to do this programmatically.</p>
  
  <p>I know it could be done manually with <a href="https://www.npmjs.com/package/resolve-pathname" rel="nofollow">resolve-pathname</a> and <code>router.push(…)</code>, but that would require access to the <code>location</code>, 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.</p>
  
  <p>Is <code>window.location.pathname</code> the right way to get the location and then use <code>router.push</code> available through <code>withRouter</code>?</p>
  
  <p>Currently I'm using this as a utility function:</p>
  
  <pre><code>import resolvePathname from 'resolve-pathname';
  
  function getPathnameFromRelativeLocation(relativeLocation) {
    let {pathname} = window.location;
    let basePath = pathname.endsWith('/') ? pathname : pathname + '/';
    return resolvePathname(relativeLocation, basePath);
  }
  </code></pre>
  
  <p>And in an event handler of a React component:</p>
  
  <pre><code>// Current path is `/books/123`
  let path = getPathnameFromRelativeLocation('write-review');
  this.props.router.push(path);
  // Current path is `/books/123/write-review`
  </code></pre>