React Router v4 - How to get current route? React Router v4 - How to get current route? reactjs reactjs

React Router v4 - How to get current route?


In the 5.1 release of react-router there is a hook called useLocation, which returns the current location object. This might useful any time you need to know the current URL.

import { useLocation } from 'react-router-dom'function HeaderView() {  const location = useLocation();  console.log(location.pathname);  return <span>Path : {location.pathname}</span>}


In react router 4 the current route is in - this.props.location.pathname.Just get this.props and verify.If you still do not see location.pathname then you should use the decorator withRouter.

This might look something like this:

import {withRouter} from 'react-router-dom';const SomeComponent = withRouter(props => <MyComponent {...props}/>);class MyComponent extends React.Component {  SomeMethod () {    const {pathname} = this.props.location;  }}


If you are using react's templates, where the end of your react file looks like this: export default SomeComponent you need to use the higher-order component (often referred to as an "HOC"), withRouter.

First, you'll need to import withRouter like so:

import {withRouter} from 'react-router-dom';

Next, you'll want to use withRouter. You can do this by change your component's export. It's likely you want to change from export default ComponentName to export default withRouter(ComponentName).

Then you can get the route (and other information) from props. Specifically, location, match, and history. The code to spit out the pathname would be:

console.log(this.props.location.pathname);

A good writeup with additional information is available here: https://reacttraining.com/react-router/core/guides/philosophy