How to Pass Props to a Component Rendered by React Router?

Find out how you can pass props to a react component when using React Router

In React Router, we can create a new route in the following way:

<Route path="/test" component={MyComponent} />

As you can see from the code above, React Router allows us to map URL paths to different React components via the component prop. However, to pass props to our component, we're going to use the render prop instead (with an inline function), for example, like so:

// React Router v4+
<Route
    path="/test"
    render={() => <MyComponent foo="bar" />}
/>

We could have passed an inline function to the component prop as well. However, while it would "work", it won't be performant because it would create a new component every render (as it uses React.createElement() internally). This leads to the existing component unmounting and the new component mounting, instead of just updating the existing component.

Please remember that the component prop takes precedence over the render prop so don't use both in the same <Route>.

When using the Route component, render receives all the same props (i.e. match, location and history) that a component would receive when using the component prop. For example:

// React Router v4+
<Route
    path="/test"
    render={(props) => <MyComponent {...props} foo="bar" />}
/>

Hope you found this post useful. It was published . Please show your love and support by sharing this post.