6
votes

I'm trying to figure out how to pass React Router's location prop to a component.

I have a route defined like so:

<Route
  path="placeholder"
  render={(props) => <Navigation {...props} />}
/>

In my Navigation component I do console.log(this.props); in the render method only to get an empty object. What gives? Isn't the location prop supposed to be automatically supplied to any component inside a Route?

By the way, I'm using react-router-dom version 4.2.2.

2
Yes you are right. The location props supposed to be automatically supplied to any component inside Route. If possible, can you please share some details about your Router setup and your Navigation Component?Cagri Yardimci

2 Answers

8
votes

You need to wrap your component with withRouter in order to inject match, history and location in your component props.

import { withRouter } from 'react-router-dom';
class Navigation extends React.Component {

  render() {
    const { match, location, history } = this.props
    return (
      <div>{location.pathname}</div>
    )
  }
}

export default withRouter(Navigation)
3
votes

You need to use the withRouter function from 'react-router-dom' on you main component where you setup Routes wrapped in a Switch and you should have access to location prop on Navigation Component by using this.props.location

App.js


Class App extends Component {
  render(){
    return (
        <Aux>
            <Switch>
                <Route path="/login" exact component={Login}/>
                <Route path="/Navigation" component={Navigation}/>
                <Redirect to="/login"/>
            </Switch>
        </Aux>
    );
  }
}
export default withRouter(App);