Blogs Technology

In router, what’s the difference between handling router component as attribute and component as children ?

In React Router, there are two main ways to define a route: as an attribute of a <Route> component, or as a child of a <Route> component.

  1. Handling route as an attribute: When you define a route as an attribute, you pass the component that should be rendered for that route as a prop to the <Route> component. For example:
import { BrowserRouter as Router, Route } from 'react-router-dom'

function App() {
  return (
    <Router>
      <Route path="/" exact component={Home} />
      <Route path="/about" component={About} />
      <Route path="/contact" component={Contact} />
    </Router>
  );
}

This way of defining a route is the most common, it is simple and easy to use, however it won’t allow you to access the match, location and history props of the <Route> component, unless you use the withRouter higher-order component.

  1. Handling route as children: When you define a route as a child, you pass the component that should be rendered for that route as a child of the <Route> component. For example:
import { BrowserRouter as Router, Route } from 'react-router-dom'

function App() {
  return (
    <Router>
      <Route path="/" exact>
        <Home />
      </Route>
      <Route path="/about">
        <About />
      </Route>
      <Route path="/contact">
        <Contact />
      </Route>
    </Router>
  );
}

This way of defining a route is less common, but it allows you to access the match, location and history props of the <Route> component without using the withRouter higher-order component. This allows you to access the routing context in the child component, it’s more flexible, but it may make your codebase more complex.

In summary, handling the route as an attribute is a simpler and more straightforward way of defining routes, while handling the route as children allows you to have more control and access to the routing context in the child component.

Leave a Reply

Your email address will not be published. Required fields are marked *