Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get current page path from react-routers browserHistory object

Outside of my components I need to query the current active URL. I'm going to set some classes on the body ( which is outside my react root ) based on this.

First attempt was to use

//Gets an array of class names that I can add to my body tag
getClassNames(window.location.pathname);

But it seems window.location.path isn't updated when React Router navigates. Surprising yes.

So I thought, ok maybe I can get this from browserHistory

import { browserHistory } from 'react-router'

But alas, I can't see a way to read the current page path from here either ( no decent API documentation seems to exist for this object)

Any tips? Seems like a simple problem, and it would be if window.location.pathname stayed in sync with the history object.

like image 927
Tim Avatar asked Mar 24 '16 02:03

Tim


People also ask

How do I get the current path in my React router?

Use the useLocation() hook to get the current route with React Router, e.g. const location = useLocation() . The hook returns the current location object. For example, you can access the pathname as location.

How do I access history object in React router?

Version 4 of React Router doesn't include a useHistory hook, so you'll have to pass down the history object via props . This is also the only way to access history in Class Components, which aren't compatible with hooks. To access the history object through props, you must ensure that your component has access to it.


1 Answers

Ok as of 2017 at least, location is available via

browserHistory.getCurrentLocation();

const location = browserHistory.getCurrentLocation();
console.log(location);
like image 83
Tim Avatar answered Nov 15 '22 17:11

Tim