react-router-dom: getting props.location from within <BrowserRouter> component

Marquizzo picture Marquizzo · Nov 15, 2017 · Viewed 10.5k times · Source

I have a simple App that uses BrowserRouter from 'react-router-dom' v4. I'm trying to access the location.pathname property from within the <BrowserRouter/> component, without avail:

class App extends Component{
  render(){
    return (
      <BrowserRouter>
        // How do I access this.props.location?
        <div className={(this.props.location.pathnme === "/account") ? "bgnd-black" : "bgnd-white"} >
          <Switch>
            <Route path="/login" component={LoginPage}/>
            <Route path="/success" component={LoginSuccess}/>
            <Route path="/account" component={MyAccount}/>
            ...
            <Route component={Error404}/>
          </Switch>
        </div>
      </BrowserRouter>
    );
  }
}

I know that I can access the app's current path location through the child components with this.props.location.pathname, but I need to access it from the parent component, just below <BrowserRouter/> to run additional logic that doesn't pertain to child components. How can I get this location?

Answer

Malvineous picture Malvineous · Feb 27, 2018

You can also do it using withRouter which has a similar result to putting the code in a render parameter and avoids the need for a "fake" <Route/>.

Essentially you put the JSX that needs to know the location in a component of its own, which is wrapped by withRouter. This supplies the location to the component:

import { withRouter } from 'react-router-dom';

const Content = withRouter(props =>
    <div className={(props.location.pathname === "/account") ? "backg...
    ...
    </div>
);

Then you use that in your main router section:

class App extends Component{
    render() {
        return (
            <BrowserRouter>
                <Content/>
                ...