Tab with React Router
Using React Router
import "./style.css";
import { MemoryRouter, Outlet, Route, Routes } from "react-router-dom";
function GroceriesTabs() {
return (
<div className="wrapper">
<Tabs>
<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();
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.
Follow updates
Join 1,000+ subscribers and receive monthly updates with the latest improvements on Examples.