React ~ Router ~ Passing Props - rohit120582sharma/Documentation GitHub Wiki

When you need to pass a prop to a component being rendered by React Route.


React Router (v4)

You can use Route's render prop instead of component prop to pass 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. This results in the existing component unmounting and the new component mounting instead of just updating the existing component.

render accepts a functional component and that function won’t get unnecessarily remounted like with component. That function will also receive all the same props that component would receive so you can pass those through to the rendered component.

<Route
    path='/dashboard'
    render={({match, location, history}) => (
        <Dashboard match={match} location={location} isAuthed={true} />
    )}
/>

React Router (v5)

In previous versions of React Router (v4), this was non-trivial since React Router was in charge of creating the element. You’d have to use the Routes render prop. However, with React Router (v5), since you’re in charge of creating the element, you’d pass a prop just like you normally would.

function Dashboard({ isAuthed }) {
    const { path, url } = useRouteMatch();

    return ...;
}

function App() {
    return (
        ...

        <Route path='/dashboard'>
            <Dashboard isAuthed={true} />
        </Route>
    );
}
⚠️ **GitHub.com Fallback** ⚠️