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.
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.
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.
Ok as of 2017 at least, location is available via
browserHistory.getCurrentLocation();
const location = browserHistory.getCurrentLocation();
console.log(location);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With