How to pass the React Router location prop to a component?
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)
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.jsClass 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);