Ariakit
/

Tab with React Router

Using React Router⁠ to create Tab links and tab panels controlled by the browser history, while maintaining keyboard navigation.

  • ğŸŽ Apple
  • 🍇 Grape
  • 🍊 Orange
import "./style.css";
import { MemoryRouter, Outlet, Route, Routes } from "react-router-dom";
import { Tab, TabList, TabPanel, Tabs } from "./tabs.tsx";
function GroceriesTabs() {
return (
<div className="wrapper">
<Tabs>
<TabList aria-label="Groceries">
<Tab to="/">Fruits</Tab>
<Tab to="/vegetables">Vegetables</Tab>
<Tab to="/meat">Meat</Tab>
</TabList>
<div className="panels">
<Outlet />
</div>
</Tabs>
</div>
);
}
function Fruits() {
return (
<ul>
<li>ğŸŽ Apple</li>
<li>🍇 Grape</li>
<li>🍊 Orange</li>
</ul>
);
}
function Vegetables() {
return (
<ul>
<li>🥕 Carrot</li>
<li>🧅 Onion</li>
<li>🥔 Potato</li>
</ul>
);
}
function Meat() {
return (
<ul>
<li>🥩 Beef</li>
<li>🍗 Chicken</li>
<li>🥓 Pork</li>
</ul>
);
}
export default function Example() {
return (
// We're using MemoryRouter for demonstration purposes. But you can use
// BrowserRouter, HashRouter, etc. depending on your needs.
<MemoryRouter>
<Routes>
<Route path="/" element={<GroceriesTabs />}>
<Route index element={<Fruits />} />
<Route path="/vegetables" element={<Vegetables />} />
<Route path="/meat" element={<Meat />} />
</Route>
</Routes>
</MemoryRouter>
);
}

Components

Controlling the Tab state

To control the selected tab state, you can pass the selectedId prop to TabProvider. This prop allows you to synchronize the tab state with other state sources, such as the browser history.

const location = useLocation();
<TabProvider selectedId={location.pathname}>

You can learn more about controlled state on the Component providers guide.

Rendering a single TabPanel

It's possible to render a single TabPanel component and use the tabId prop to control the selected tab.

const selectedId = tab.useState("selectedId");
<TabPanel tabId={selectedId}>
<Outlet />

Stay tuned

Join 1,000+ subscribers and receive monthly tips & updates on new Ariakit content.

No spam. Unsubscribe anytime. Read latest issue⁠