How to use React Router with a layout page or multiple components per page?

Sometimes, we want to use React Router with a layout page or multiple components per page.

In this article, we’ll look at how to use React Router with a layout page or multiple components per page.

How to use React Router with a layout page or multiple components per page?

To use React Router with a layout page or multiple components per page, we can create an array with the routes and layout component value for each route.

And then we can render the array into routes.

For instance, we write

const routes = [
  {
    layout: Layout1,
    subRoutes: [
      {
        path: "/route1/:id/:token",
        component: SetPassword,
      },
      {
        exact: true,
        path: "/",
        component: SignIn,
      },
    ],
  },
  {
    layout: Layout2,
    subRoutes: [
      {
        path: "/route2",
        component: Home,
      },
    ],
  },
];

const App = () => {
  //...
  return (
    <Switch>
      {routes.map((route, i) => (
        <Route
          key={i}
          exact={route.subRoutes.some((r) => r.exact)}
          path={route.subRoutes.map((r) => r.path)}
        >
          <route.layout>
            {route.subRoutes.map((subRoute, i) => (
              <Route key={i} {...subRoute} />
            ))}
          </route.layout>
        </Route>
      ))}
    </Switch>
  );
};

to define the routes array with the layout and subRoutes properties in each object entry.

Then in App, we call routes.map to render each route by calling map with a callback that returns an Router component wrapped around a route.layout component.

And then we render the route.subRoutes items into Routes by calling route.subRoutes.map with a callback to return the Route.

If route.layout renders the children prop then the components inside it should show.

Conclusion

To use React Router with a layout page or multiple components per page, we can create an array with the routes and layout component value for each route.

And then we can render the array into routes.