React router gets the current location on the main component of the router

I would like to know how to get the current location from the component that I used to determine my routes. For example, I have a Routes component that contains all routes, for example:

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 in other components, it returns undefined .

On other components, I need to use withRouter to have access to location information. But I cannot use it with the Routes component because it will throw an error.

I really don't need pathname , I just want to check which route the user has, because I get different header content when accessing a specific page.

+5
source share
1 answer

Wrap your heading in <Route> , which is always displayed. Then you will have access to everything through the details.

 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> ); } }; 
+3
source

Source: https://habr.com/ru/post/1266723/


All Articles