6

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.

Saugat
  • 1,309
  • 14
  • 22
celsomtrindade
  • 4,501
  • 18
  • 61
  • 116
  • One solution is to do `location.pathname` which is not related to react-router but comes from the browser instead. – Saugat Apr 14 '17 at 03:00
  • @SaugatAcharya Yeah.. This or moving the verification to another component would be my other options. I just wanted to check if this was possible within the main component. – celsomtrindade Apr 14 '17 at 03:01
  • Are you getting anything in `this.props.location`? – Saugat Apr 14 '17 at 03:05
  • @SaugatAcharya No. Since that component is connected with redux, only the data maped to props. However, even when disabling the redux on the component, I can't access the location. – celsomtrindade Apr 14 '17 at 03:07
  • Just did a quick check, `this.props.location` is in fact accessible from components. Try using react-dev-tools to see what's wrong. Not sure what you are doing with redux. – Saugat Apr 14 '17 at 03:24
  • are you using withRouter like `withRouter(connect(...)(MyComponent)` – Shubham Khatri Apr 14 '17 at 04:18

1 Answers1

5

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>
        );
    }
};
Tyler McGinnis
  • 34,836
  • 16
  • 72
  • 77