Tab with React Router

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

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


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 />

Follow updates

Join 1,000+ subscribers and receive monthly updates with the latest improvements on Examples.

Read latest issue

No Spam. Unsubscribe at any time.