Why do programmers use component property in react routing?

Viewed 44

I'm studying react nowadays. I found that programmers usually use component property when routing in react. So, for route a component named Menu, they write code like

<Route exact path='/menu' component={ Menu } />

rather than

<Route exact path='/menu'> <Menu /> </Route>

I think the second way is much more convenient when giving props to Menu component. So my question is, what is the benefit of writing code as the first way?

Thank you.

1 Answers

It is all about the usecase. There are following ways we can declare a route:

  1. component

    <Route to="/home" component={Home} />
    

    One add routes this way when one doesn't want to have the control to pass any props to the Component, simple passing the Component Object to the route as a prop.

  2. render

    <Route to="/home" render={props => <Home {...props} />} />
    

    One add routes this way when one want to have the control to pass any props to the Component and even update the existing component props.

  3. children

    <Route exact path='/home'> <Home/> </Route>
    

    This is another way to pass the route component as a child to the Route component. you can again pass the props or maybe wrap the component into another component or some html structure.

It is simply a developer's choice to pick one for its solution. Developer these days use many methods or frameworks to induce routing in the react app. I personally like the first one, as it is clean, ensures prop-types and give warnings on any violation and also I don't have a use case or prop passing on route level.

Related