Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React router difference between render and children prop

I wanted to understand the exact differences between the 2 ways of writing React <Route /> i.e. one with "render" and other with "children" prop;

// With "render"
    <Route
          path={route.path}
          render={props => (
            // pass the sub-routes down to keep nesting
            <route.component {...props} routes={route.routes} />
          )}
        />

// With "children"
    <Route
            path={route.path}
            exact={route.exact}
            children={props => <route.component {...props} routes={route.routes} />}
          />

Also, with the 2nd use case (i.e. with "children"), what difference does it make when exact property is true v/s false ?

like image 946
copenndthagen Avatar asked Sep 05 '25 01:09

copenndthagen


1 Answers

From the docs of

React Router's render function

This allows for convenient inline rendering and wrapping without the undesired remounting explained above.Instead of having a new React element created for you using the component prop, you can pass in a function to be called when the location matches

And

React Router's children function

Sometimes you need to render whether the path matches the location or not. In these cases, you can use the function children prop. It works exactly like render except that it gets called whether there is a match or not.

The main difference as per what I understand is that when we pass a component as children prop then that component will get rendered even if the location matches or not.

I have created a sample app in order to simulate the same, here is the app

like image 101
Nithish Avatar answered Sep 07 '25 13:09

Nithish