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
.
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With