I'd like to know how to get the current location from the component I've used to define my routes. For example, I have a component called Routes, which contains all the routes, like this:
class Routes extends React.Component {
render() {
return (
<Router>
<Nav />
<header>{customHeader}</header>
<Switch>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
// Other routes
</Switch>
</Router>
);
}
};
However, when I try to access this.props.location.pathname
as I do in other components, it returns undefined
.
On the other components I need to use withRouter
in order to be able to access the location
information. But I can't use it with the Routes
component, because it will throw an error.
I don't actually need the pathname
, I just want to check what route the user is, because I'll render a different header content when accessing a specific page.
Use the window object to get the current URL in React, e.g. window. location. href returns a string containing the whole URL. If you need to access the path, use window.
The useLocation hook returns the location object that represents the current URL. You can think about it like a useState that returns a new location whenever the URL changes.
Wrap your header in a <Route>
that always renders. Then you'll have access to everything via props.
class Routes extends React.Component {
render() {
return (
<Router>
<Nav />
<Route render={(props) => {
console.log(props.location)
return (
<header>{customHeader}</header>
)
}} />
<Switch>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
// Other routes
</Switch>
</Router>
);
}
};
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