← Components

Navigation · Material 3: Navigation bar, Navigation rail, Navigation drawer

Navigation

The app's main destinations. One component, three layouts: bar (phones), rail (tablets), drawer (desktop). The active pill slides between items.

Examples and variants

Bar, rail, drawer

Switch the variant; the items stay the same.

Example
function NavigationVariants() {
  const [active, setActive] = useState("Home")
  const [variant, setVariant] = useState<"bar" | "rail" | "drawer">("drawer")
  return (
    <div className="flex w-full flex-col items-center gap-4">
      <div className="flex gap-2">
        {(["bar", "rail", "drawer"] as const).map((v) => (
          <Button key={v} size="sm" variant={variant === v ? "primary" : "secondary"} onClick={() => setVariant(v)}>
            {v}
          </Button>
        ))}
      </div>
      <div className="overflow-hidden rounded-(--shape-lg) shadow-1">
        <Navigation variant={variant} className={variant === "bar" ? "w-80" : undefined}>
          {destinations.map((item) => (
            <NavigationItem
              key={item.label}
              href="#"
              icon={item.icon}
              label={item.label}
              badge={item.badge}
              active={active === item.label}
              onClick={(event) => {
                event.preventDefault()
                setActive(item.label)
              }}
            />
          ))}
        </Navigation>
      </div>
    </div>
  )
}

Spec drawing

Measured from the live component at default density. Each code maps to the token that sets it; change the token and the drawing follows.

Install

With the CLI

The shadcn CLI only delivers files: it copies our code from the Isotopi registry into your project and installs the packages it uses. Add the foundation once, then the component.

Terminal
npx shadcn@latest add https://isotopi.com/r/minimal.json
npx shadcn@latest add https://isotopi.com/r/navigation.json

By hand

No CLI needed. Add the foundation once (see Getting started), then follow these steps. They include every component this one builds on.

  1. Install the packages it uses.

    Terminal
    npm install cn
  2. Copy this file to the same paths in your project. Imports use the @/ alias for your project root.

    • components/ui/navigation.tsxnavigation
      components/ui/navigation.tsx
      "use client"
      
      import * as React from "react"
      import { cn } from "cn"
      import { layoutTop } from "@/lib/motion/layout-offset"
      
      /*
        Navigation: one component for the app's main destinations (Material 3's
        navigation bar, rail and drawer). The items stay the same; the layout
        changes with the variant:
        - bar: bottom of the screen on phones, icons with short labels.
        - rail: a narrow column on tablets, icons over labels.
        - drawer: a wide column on desktop, icon and label in a row.
        The active indicator slides between items on a spring.
      */
      type Variant = "bar" | "rail" | "drawer"
      const VariantContext = React.createContext<Variant>("drawer")
      
      function Navigation({
        className,
        variant = "drawer",
        children,
        "aria-label": label = "Main",
        ...props
      }: React.ComponentProps<"nav"> & { variant?: Variant }) {
        const listRef = React.useRef<HTMLUListElement>(null)
        const [box, setBox] = React.useState<{ top: number; left: number; width: number; height: number } | null>(null)
      
        React.useLayoutEffect(() => {
          const list = listRef.current
          if (!list) return
          const measure = () => {
            // Bar and rail: the pill wraps the icon. Drawer: the whole row.
            const active =
              list.querySelector<HTMLElement>("[aria-current=page] [data-slot=navigation-indicator-anchor]") ??
              list.querySelector<HTMLElement>("[aria-current=page]")
            if (!active) return setBox(null)
            const listBox = list.getBoundingClientRect()
            const box = active.getBoundingClientRect()
            // Horizontal from the box (items reflow between variants); vertical from layout.
            setBox({ top: layoutTop(active, list), left: box.left - listBox.left, width: active.offsetWidth, height: active.offsetHeight })
          }
          measure()
          const observer = new MutationObserver(measure)
          observer.observe(list, { subtree: true, attributes: true, attributeFilter: ["aria-current"] })
          const resize = new ResizeObserver(measure)
          resize.observe(list)
          return () => {
            observer.disconnect()
            resize.disconnect()
          }
        }, [variant])
      
        return (
          <VariantContext.Provider value={variant}>
            <nav
              data-slot="navigation"
              data-variant={variant}
              aria-label={label}
              className={cn(
                "bg-(--nav-container)",
                variant === "bar" && "h-(--nav-bar-height) w-full px-2",
                variant === "rail" && "w-(--nav-rail-width) py-3",
                variant === "drawer" && "w-(--nav-drawer-width) p-3",
                className
              )}
              {...props}
            >
              <ul ref={listRef} className={cn("relative flex", variant === "bar" ? "h-full items-center justify-around" : "flex-col gap-1", variant === "rail" && "items-center")}>
                {box ? (
                  <span
                    aria-hidden
                    className="navigation-indicator pointer-events-none absolute rounded-(--nav-item-corner) bg-(--nav-item-active)"
                    style={{ top: box.top, left: box.left, width: box.width, height: box.height }}
                  />
                ) : null}
                {children}
              </ul>
            </nav>
          </VariantContext.Provider>
        )
      }
      
      function NavigationItem({
        className,
        icon,
        label,
        active = false,
        badge,
        render,
        ...props
      }: Omit<React.ComponentProps<"a">, "children"> & {
        icon: React.ReactNode
        label: string
        active?: boolean
        badge?: React.ReactNode
        /** Render as your router's link: render={<Link href="/inbox" />}. */
        render?: React.ReactElement<Record<string, unknown>>
      }) {
        const variant = React.useContext(VariantContext)
        const stacked = variant !== "drawer"
        const content = (
          <>
            <span
              data-slot={stacked ? "navigation-indicator-anchor" : undefined}
              className={cn(
                "relative z-[1] inline-flex items-center justify-center [&_svg]:size-(--size-icon-lg)",
                stacked && "h-(--size-control-sm) w-14 rounded-(--nav-item-corner)"
              )}
            >
              {icon}
              {badge && stacked ? <span className="absolute -top-0.5 right-2">{badge}</span> : null}
            </span>
            <span className={cn("relative z-[1]", stacked ? "text-caption normal-case" : "text-sm")}>{label}</span>
            {badge && !stacked ? <span className="relative z-[1] ms-auto">{badge}</span> : null}
          </>
        )
        const itemClass = cn(
          "flex outline-none focus-visible:shadow-(--focus-ring) text-muted-foreground hover:text-foreground aria-[current=page]:text-(--nav-item-active-label) aria-[current=page]:font-medium",
          stacked ? "flex-col items-center gap-1 rounded-(--shape-md) px-1 py-1" : "h-(--nav-item-height) items-center gap-3 rounded-(--nav-item-corner) px-4 hover:bg-(--nav-item-container-hover) active:bg-(--nav-item-container-pressed)",
          className
        )
        const shared = { "data-slot": "navigation-item", "aria-current": active ? ("page" as const) : undefined, className: itemClass }
        return (
          <li className={cn(variant === "bar" && "flex-1", "flex justify-center", variant === "drawer" && "block")}>
            {render ? React.cloneElement(render, { ...shared, ...props, children: content }) : <a {...shared} {...props}>{content}</a>}
          </li>
        )
      }
      
      export { Navigation, NavigationItem }
      

Imports

What the examples on this page import:

Imports
import {
import { AppBar } from "@/components/ui/app-bar"
import { Badge } from "@/components/ui/badge"
import { Breadcrumb } from "@/components/ui/breadcrumb"
import { Button } from "@/components/ui/button"
import { DropdownMenuItem } from "@/components/ui/dropdown-menu"
import { Fab } from "@/components/ui/fab"
import { Navigation, NavigationItem } from "@/components/ui/navigation"
import { Pagination } from "@/components/ui/pagination"
import { SplitButton } from "@/components/ui/split-button"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Toolbar, ToolbarButton, ToolbarGroup, ToolbarSeparator } from "@/components/ui/toolbar"

Anatomy

  1. 1Container · --nav-container; --nav-bar-height, --nav-rail-width, --nav-drawer-width.
  2. 2Item · Icon and label; drawer items use --nav-item-height.
  3. 3Active indicator · --nav-item-active, --nav-item-corner.
  4. 4Badge · Optional count or dot on the icon.

Props

PropTypeDefaultDescription
variant"bar" | "rail" | "drawer""drawer"Layout. Switch by screen size.
NavigationItem icon, labelReactNode, string—Required.
NavigationItem activeboolean—Sets aria-current=page.
NavigationItem renderReactElement—Your router's Link.

Tokens

Every visual spec is a component token in styles/tokens/components.css, pointing at a semantic token. Change a token to restyle the component; themes change the semantic layer.

TokenPoints toLightDark
--nav-item-heightvar(--size-row)40pxsame
--nav-item-cornervar(--shape-full)999pxsame
--nav-item-container-hovervar(--color-bg-hover)oklch(0.965 0.005 95)oklch(0.22 0 0)
--nav-item-container-pressedvar(--color-bg-pressed)oklch(0.94 0.007 95)oklch(0.27 0 0)
--nav-item-activevar(--color-bg-selected)color-mix(in oklch, var(--ref-select) 12%, transparent)color-mix(in oklch, var(--ref-select) 16%, transparent)
--nav-item-active-labelvar(--on-surface)oklch(0.22 0.01 260)oklch(1 0 0)
--nav-bar-heightvar(--space-16)64pxsame
--nav-rail-widthvar(--space-20)80pxsame
--nav-drawer-widthvar(--layout-sidebar)256pxsame
--nav-containervar(--surface-container-low)oklch(0.985 0.004 95)oklch(0.17 0 0)

Motion

TriggerWhat happensTokens
SelectThe active pill slides to the new item on a spring.--spring-snappy

Calm keeps the motion without overshoot. Still (and reduced motion) keeps a designed frame with no movement.

Accessibility

  • A nav landmark with a label; the current item has aria-current=page.
  • Labels stay visible in every variant.

Usage

Do

  • 3 to 5 destinations in a bar; up to 7 in a rail; more in a drawer.

Don’t

  • Don't use for actions (use a Toolbar or Menu).

Code

components/ui/navigation.tsx
"use client"

import * as React from "react"
import { cn } from "cn"
import { layoutTop } from "@/lib/motion/layout-offset"

/*
  Navigation: one component for the app's main destinations (Material 3's
  navigation bar, rail and drawer). The items stay the same; the layout
  changes with the variant:
  - bar: bottom of the screen on phones, icons with short labels.
  - rail: a narrow column on tablets, icons over labels.
  - drawer: a wide column on desktop, icon and label in a row.
  The active indicator slides between items on a spring.
*/
type Variant = "bar" | "rail" | "drawer"
const VariantContext = React.createContext<Variant>("drawer")

function Navigation({
  className,
  variant = "drawer",
  children,
  "aria-label": label = "Main",
  ...props
}: React.ComponentProps<"nav"> & { variant?: Variant }) {
  const listRef = React.useRef<HTMLUListElement>(null)
  const [box, setBox] = React.useState<{ top: number; left: number; width: number; height: number } | null>(null)

  React.useLayoutEffect(() => {
    const list = listRef.current
    if (!list) return
    const measure = () => {
      // Bar and rail: the pill wraps the icon. Drawer: the whole row.
      const active =
        list.querySelector<HTMLElement>("[aria-current=page] [data-slot=navigation-indicator-anchor]") ??
        list.querySelector<HTMLElement>("[aria-current=page]")
      if (!active) return setBox(null)
      const listBox = list.getBoundingClientRect()
      const box = active.getBoundingClientRect()
      // Horizontal from the box (items reflow between variants); vertical from layout.
      setBox({ top: layoutTop(active, list), left: box.left - listBox.left, width: active.offsetWidth, height: active.offsetHeight })
    }
    measure()
    const observer = new MutationObserver(measure)
    observer.observe(list, { subtree: true, attributes: true, attributeFilter: ["aria-current"] })
    const resize = new ResizeObserver(measure)
    resize.observe(list)
    return () => {
      observer.disconnect()
      resize.disconnect()
    }
  }, [variant])

  return (
    <VariantContext.Provider value={variant}>
      <nav
        data-slot="navigation"
        data-variant={variant}
        aria-label={label}
        className={cn(
          "bg-(--nav-container)",
          variant === "bar" && "h-(--nav-bar-height) w-full px-2",
          variant === "rail" && "w-(--nav-rail-width) py-3",
          variant === "drawer" && "w-(--nav-drawer-width) p-3",
          className
        )}
        {...props}
      >
        <ul ref={listRef} className={cn("relative flex", variant === "bar" ? "h-full items-center justify-around" : "flex-col gap-1", variant === "rail" && "items-center")}>
          {box ? (
            <span
              aria-hidden
              className="navigation-indicator pointer-events-none absolute rounded-(--nav-item-corner) bg-(--nav-item-active)"
              style={{ top: box.top, left: box.left, width: box.width, height: box.height }}
            />
          ) : null}
          {children}
        </ul>
      </nav>
    </VariantContext.Provider>
  )
}

function NavigationItem({
  className,
  icon,
  label,
  active = false,
  badge,
  render,
  ...props
}: Omit<React.ComponentProps<"a">, "children"> & {
  icon: React.ReactNode
  label: string
  active?: boolean
  badge?: React.ReactNode
  /** Render as your router's link: render={<Link href="/inbox" />}. */
  render?: React.ReactElement<Record<string, unknown>>
}) {
  const variant = React.useContext(VariantContext)
  const stacked = variant !== "drawer"
  const content = (
    <>
      <span
        data-slot={stacked ? "navigation-indicator-anchor" : undefined}
        className={cn(
          "relative z-[1] inline-flex items-center justify-center [&_svg]:size-(--size-icon-lg)",
          stacked && "h-(--size-control-sm) w-14 rounded-(--nav-item-corner)"
        )}
      >
        {icon}
        {badge && stacked ? <span className="absolute -top-0.5 right-2">{badge}</span> : null}
      </span>
      <span className={cn("relative z-[1]", stacked ? "text-caption normal-case" : "text-sm")}>{label}</span>
      {badge && !stacked ? <span className="relative z-[1] ms-auto">{badge}</span> : null}
    </>
  )
  const itemClass = cn(
    "flex outline-none focus-visible:shadow-(--focus-ring) text-muted-foreground hover:text-foreground aria-[current=page]:text-(--nav-item-active-label) aria-[current=page]:font-medium",
    stacked ? "flex-col items-center gap-1 rounded-(--shape-md) px-1 py-1" : "h-(--nav-item-height) items-center gap-3 rounded-(--nav-item-corner) px-4 hover:bg-(--nav-item-container-hover) active:bg-(--nav-item-container-pressed)",
    className
  )
  const shared = { "data-slot": "navigation-item", "aria-current": active ? ("page" as const) : undefined, className: itemClass }
  return (
    <li className={cn(variant === "bar" && "flex-1", "flex justify-center", variant === "drawer" && "block")}>
      {render ? React.cloneElement(render, { ...shared, ...props, children: content }) : <a {...shared} {...props}>{content}</a>}
    </li>
  )
}

export { Navigation, NavigationItem }