Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React router get current location on main router component

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.

like image 441
celsomtrindade Avatar asked Apr 14 '17 02:04

celsomtrindade


People also ask

How do I get the current page in react?

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.

Which react router hook gives you the location object?

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.


1 Answers

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>
        );
    }
};
like image 169
Tyler McGinnis Avatar answered Oct 23 '22 04:10

Tyler McGinnis