Sidebar

Each logical "route" has two components, one for the sidebar and one for the main area. We want to render both in different places when the path matches the current URL.

We are going to use this route config in 2 spots: once for the sidebar and once in the main content section. Each spot needs its own <Routes> wrapper (a bare <Route> can't be rendered outside one), but both independently match against the very same current URL.

You can render a <Route> matching a given path in as many places as you want in your app, each inside its own <Routes>. So, a sidebar or breadcrumbs or anything else that requires you to render multiple things in multiple places at the same URL is nothing more than multiple <Routes> trees sharing the same route config.


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

const routes = [
  { path: "/", sidebar: () => <div>home!</div>, main: () => <h2>Home</h2> },
  { path: "/bubblegum", sidebar: () => <div>bubblegum!</div>, main: () => <h2>Bubblegum</h2> },
  { path: "/shoelaces", sidebar: () => <div>shoelaces!</div>, main: () => <h2>Shoelaces</h2> },
];

export default function SidebarExample() {
  return (
    <Router>
      <div style={{ display: "flex" }}>
        <div style={{ padding: "10px", width: "40%", background: "#f0f0f0" }}>
          <ul style={{ listStyleType: "none", padding: 0 }}>
            <li><Link to="/">Home</Link></li>
            <li><Link to="/bubblegum">Bubblegum</Link></li>
            <li><Link to="/shoelaces">Shoelaces</Link></li>
          </ul>
          <Routes>
            {routes.map((route, index) => (
              <Route key={index} path={route.path} element={route.sidebar()} />
            ))}
          </Routes>
        </div>
        <div style={{ flex: 1, padding: "10px" }}>
          <Routes>
            {routes.map((route, index) => (
              <Route key={index} path={route.path} element={route.main()} />
            ))}
          </Routes>
        </div>
      </div>
    </Router>
  );
}