Route Config

Some developers like a centralized route config array. React is great at mapping an array into components. Passing extra data like a "routes" sub-array down to the matched component used to require <Route render={props => ...}>, which no longer exists – but since "element" already takes a JSX element you constructed yourself, you can just pass whatever extra props you like directly.

Note the parent route's path ends in /* : that lets its component render its own nested <Routes> for the sub-paths, matching against whatever is left of the URL after "/tacos" is consumed. The sub-route paths are written relative to that (just "bus", not "/tacos/bus").


import React from "react";
import { BrowserRouter as Router, Routes, Route, Link } from "react-router";

const routes = [
  { path: "/sandwiches", component: Sandwiches },
  {
    path: "/tacos/*",
    component: Tacos,
    routes: [
      { path: "bus", component: Bus },
      { path: "cart", component: Cart },
    ],
  },
];

export default function RouteConfigExample() {
  return (
    <Router>
      <div>
        <ul>
          <li><Link to="/tacos">Tacos</Link></li>
          <li><Link to="/sandwiches">Sandwiches</Link></li>
        </ul>
        <Routes>
          {routes.map((route, i) => (
            <Route key={i} path={route.path} element={<RouteWithSubRoutes {...route} />} />
          ))}
        </Routes>
      </div>
    </Router>
  );
}
function RouteWithSubRoutes(route) {
  return <route.component routes={route.routes} />;
}
function Sandwiches() { return <h2>Sandwiches</h2>; }
function Tacos({ routes }) {
  return (
    <div>
      <h2>Tacos</h2>
      <ul>
        <li><Link to="/tacos/bus">Bus</Link></li>
        <li><Link to="/tacos/cart">Cart</Link></li>
      </ul>
      <Routes>
        {routes.map((route, i) => (
          <Route key={i} path={route.path} element={<RouteWithSubRoutes {...route} />} />
        ))}
      </Routes>
    </div>
  );
}
function Bus() { return <h3>Bus</h3>; }
function Cart() { return <h3>Cart</h3>; }