Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass the React Router location prop to a component?

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.

like image 557
Ralph David Abernathy Avatar asked Jul 06 '18 05:07

Ralph David Abernathy


People also ask

How do I pass a prop to a component?

To pass props, add them to the JSX, just like you would with HTML attributes. To read props, use the function Avatar({ person, size }) destructuring syntax.

Which routing properties will pass to the component?

Passing props to a Component When you use component, the router uses React. createElement to create a new React element from the given component. That means if you provide an inline function to the component prop, you would create a new component every render.

How do you pass props to a component rendered by React router V6?

V6 doesn't export a Switch component, it was replaced by a Routes component. Swap the Switch for the Routes component and rename your Routes component to something else to avoid the name collision. From here the home prop should either be treated as truthy/falsey.


1 Answers

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)
like image 54
Liam Avatar answered Sep 28 '22 17:09

Liam