When you make use of react-router
, you can identify which path you are currently on by simply reading the location.pathname
from the props.
If the component in which you are trying to access location.pathname
isn't connected to the Route
directly or isn't receiving the Router
props, you can wrap it with the withRouter
HOC to access router props.
Also, router has a prop called as match
which gives the closest match route information to the component that you are using that in
For example, in a Route configuration
<Route path="/" component={Home} />
Home.jsx
render() {
console.log(this.props.match.path);
return (
<div>
<Route path="/user" component={User}/>
</div>
)
}
So in the above case if you are visiting the url: /user
, and if you log this.props.match.url
, it will result in /
which isn't the desired result that you might be looking for.
A way to get around this is to use matchPath
method that is provided by react-router
A typical usage of it would be
const { match } = this.props;
let { hash } = window.location;
[hash] = hash.slice(1).split('?');
// match.path is the path that is matched till the parent
const customMatch = matchPath(hash, {
path: `${match.path}user`,
exact: false,
strict: false
});
console.log(customMatch)