Components
Navbar
The bar at the top of a page: a brand, links and actions, with a menu for small screens.
Introduction
The navbar is how people move around your site, so it appears on every page. It puts the brand, the main links and a few actions in one row, and on small screens it folds the links into a menu that a button opens.
- Built from small parts you arrange yourself: groups of content, a brand, links, a toggle and a menu.
- Marks the current page with
isActive, and tells screen readers witharia-current. - Dropdown menus for a short list of entries, and a mega menu for a wide panel of links in sections.
- Folds into a menu below a breakpoint you choose. The toggle button reports whether the menu is open, and Escape closes it.
- Can stay at the top while the page scrolls, with a border and a blurred background.
Links use next/link, so navigation stays on the client.
Installation
centerUI has no CLI or registry yet: components are copied into your project. Navbar uses Button for the toggle and Container for its width, so it needs both.
# bun
bun add react-aria-components tailwind-variants tailwind-merge clsx
# pnpm
pnpm add react-aria-components tailwind-variants tailwind-merge clsx
# npm
npm install react-aria-components tailwind-variants tailwind-merge clsxAdd Button and Container first (see their Manual installation), then follow the steps below.
Manual installation
Copy these files into your project and keep the paths, or adjust the imports.
1. Add the styles
src/types/navbar-styles.tsShow code
import { tv } from "tailwind-variants";
import type { NavbarCollapse } from "./navbar-context";
export const navbarStyles = tv({
slots: {
root: "w-full text-fg",
bar: "flex items-center gap-4",
item: [
"inline-flex cursor-pointer items-center gap-1.5 rounded-md px-3 py-1.5 text-sm text-muted-fg outline-none transition-colors",
"hover:text-fg",
"focus-visible:ring-2 focus-visible:ring-ring",
"data-active:font-medium data-active:text-fg",
],
brand:
"flex shrink-0 items-center gap-2 rounded-md font-semibold tracking-tight outline-none focus-visible:ring-2 focus-visible:ring-ring",
menu: "absolute inset-x-0 top-full z-30 border-b bg-bg/95 shadow-lg backdrop-blur-md",
menuInner: "flex flex-col gap-1 px-4 py-3 sm:px-6",
// The button that opens a dropdown or a mega menu. It is styled like an
// item, with a chevron that turns over while the menu is open.
trigger: "group/navbar-trigger aria-expanded:text-fg",
chevron:
"size-3.5 shrink-0 transition-transform group-aria-expanded/navbar-trigger:rotate-180",
dropdown:
"popover z-50 min-w-56 overflow-hidden rounded-xl border bg-card text-card-fg shadow-lg",
dropdownItem: [
"flex cursor-default items-start gap-2.5 rounded-lg px-2.5 py-2 text-sm outline-none",
"data-focused:bg-muted data-disabled:opacity-50",
],
megaPopover:
"popover z-50 w-(--trigger-width) border-b bg-bg text-fg shadow-lg",
megaLink: [
"flex items-start gap-3 rounded-lg px-3 py-2.5 text-sm outline-none transition-colors",
"hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring",
],
sectionTitle:
"px-3 pb-1 text-xs font-medium tracking-wide text-muted-fg uppercase",
menuItem: [
"flex w-full cursor-pointer items-center gap-2 rounded-md px-3 py-2 text-left text-base text-muted-fg outline-none transition-colors",
"hover:bg-muted hover:text-fg",
"focus-visible:ring-2 focus-visible:ring-ring",
"data-active:bg-muted data-active:font-medium data-active:text-fg",
],
},
variants: {
isSticky: {
true: { root: "sticky top-0 z-40" },
false: { root: "relative" },
},
isBordered: {
true: { root: "border-b" },
false: {},
},
isBlurred: {
true: { root: "bg-bg/80 backdrop-blur-md" },
false: { root: "bg-bg" },
},
size: {
sm: { bar: "h-12" },
md: { bar: "h-14" },
lg: { bar: "h-16" },
},
},
defaultVariants: {
isSticky: false,
isBordered: true,
isBlurred: true,
size: "md",
},
});
// What is shown only when the navbar is collapsed: the toggle button and the
// menu. They are hidden from the breakpoint up. Written out in full so
// Tailwind can see every class.
export const showWhenCollapsed: Record<NavbarCollapse, string> = {
sm: "sm:hidden",
md: "md:hidden",
lg: "lg:hidden",
always: "",
never: "hidden",
};
// What is shown only when the navbar is NOT collapsed: the links. They are
// hidden below the breakpoint.
export const showWhenExpanded: Record<NavbarCollapse, string> = {
sm: "hidden sm:flex",
md: "hidden md:flex",
lg: "hidden lg:flex",
always: "hidden",
never: "flex",
};2. Add the context
It shares whether the menu is open between the navbar and its parts.
src/types/navbar-context.tsShow code
import { createContext, type RefObject, useContext } from "react";
import type { VariantProps } from "tailwind-variants";
import type { containerStyles } from "./container-styles";
/**
* Where the navbar folds its links into a menu: below `sm`, `md` or `lg`,
* `"always"`, or `"never"`.
*/
export type NavbarCollapse = "sm" | "md" | "lg" | "always" | "never";
/** What a Navbar shares with its toggle, menu and menu items. */
export interface NavbarContextValue {
collapse: NavbarCollapse;
isMenuOpen: boolean;
setMenuOpen: (isOpen: boolean) => void;
/** Ids that tie the toggle button to the menu it opens. */
menuId: string;
toggleId: string;
/** The bar itself. A mega menu opens under it and takes its width. */
barRef: RefObject<HTMLElement | null>;
/** The widest the bar's content gets, which a mega menu's content follows. */
maxWidth: VariantProps<typeof containerStyles>["size"];
}
const NavbarContext = createContext<NavbarContextValue | null>(null);
export const NavbarProvider = NavbarContext.Provider;
/** The enclosing Navbar's state. Throws outside of a Navbar. */
export function useNavbar() {
const context = useContext(NavbarContext);
if (!context) {
throw new Error(
"NavbarToggle, NavbarMenu and NavbarMenuItem must be used inside a Navbar.",
);
}
return context;
}3. Add the Navbar file
src/components/ui/navbar/navbar.tsxShow code
"use client";
import Link from "next/link";
import { useRouter } from "next/navigation";
import {
type ComponentProps,
type ComponentPropsWithoutRef,
type ReactNode,
useId,
useRef,
useState,
} from "react";
import { RouterProvider } from "react-aria-components";
import { MenuIcon, XIcon } from "@/components/icons";
import { Button } from "@/components/ui/button/button";
import {
Container,
type ContainerProps,
} from "@/components/ui/container/container";
import { cn } from "@/lib/cn";
import {
type NavbarCollapse,
NavbarProvider,
useNavbar,
} from "@/types/navbar-context";
import {
navbarStyles,
showWhenCollapsed,
showWhenExpanded,
} from "@/types/navbar-styles";
export interface NavbarProps {
/** Names the navigation for screen readers. Defaults to "Main". */
"aria-label"?: string;
/** Stay at the top of the screen while the page scrolls. */
isSticky?: boolean;
/** A line under the bar. */
isBordered?: boolean;
/** A translucent background that blurs what scrolls under it. Otherwise it is solid. */
isBlurred?: boolean;
/** Height of the bar. */
size?: "sm" | "md" | "lg";
/** The widest the content gets, as a Container size. */
maxWidth?: ContainerProps["size"];
/**
* Where the links fold into the menu: below the `sm`, `md` (default) or `lg`
* breakpoint. `"always"` keeps them in the menu, `"never"` keeps them in
* the bar.
*/
collapse?: NavbarCollapse;
/** Whether the menu is open, for a controlled navbar. */
isMenuOpen?: boolean;
/** Whether the menu starts open, for an uncontrolled navbar. */
defaultMenuOpen?: boolean;
onMenuOpenChange?: (isOpen: boolean) => void;
className?: string;
children?: ReactNode;
}
/**
* The bar at the top of a page: a brand, links, actions, and on small screens
* a button that opens the links as a menu. Compose it from `NavbarContent`
* (the groups), `NavbarBrand`, `NavbarItem` (the links), `NavbarToggle` and
* `NavbarMenu` with `NavbarMenuItem`.
*
* Escape closes the menu and puts focus back on the toggle.
*
* @example
* <Navbar isSticky>
* <NavbarContent>
* <NavbarToggle />
* <NavbarBrand href="/">centerUI</NavbarBrand>
* </NavbarContent>
* <NavbarContent isCollapsible justify="center">
* <NavbarItem href="/docs" isActive>Docs</NavbarItem>
* </NavbarContent>
* <NavbarMenu>
* <NavbarMenuItem href="/docs">Docs</NavbarMenuItem>
* </NavbarMenu>
* </Navbar>
*/
export function Navbar({
"aria-label": ariaLabel = "Main",
isSticky,
isBordered,
isBlurred,
size,
maxWidth = "xl",
collapse = "md",
isMenuOpen,
defaultMenuOpen = false,
onMenuOpenChange,
className,
children,
}: NavbarProps) {
const styles = navbarStyles({ isSticky, isBordered, isBlurred, size });
const id = useId();
const menuId = `${id}-menu`;
const toggleId = `${id}-toggle`;
const barRef = useRef<HTMLElement>(null);
// Links inside dropdown menus should navigate on the client, like the
// `next/link` ones do.
const router = useRouter();
const isControlled = isMenuOpen !== undefined;
const [inner, setInner] = useState(defaultMenuOpen);
const open = isControlled ? isMenuOpen : inner;
function setMenuOpen(next: boolean) {
if (!isControlled) setInner(next);
onMenuOpenChange?.(next);
}
return (
<NavbarProvider
value={{
collapse,
isMenuOpen: open,
setMenuOpen,
menuId,
toggleId,
barRef,
maxWidth,
}}
>
{/* biome-ignore lint/a11y/noStaticElementInteractions: only listens for Escape bubbling up from the controls inside */}
<header
ref={barRef}
className={cn(styles.root(), className)}
onKeyDown={(event) => {
if (event.key === "Escape" && open) {
setMenuOpen(false);
document.getElementById(toggleId)?.focus();
}
}}
>
<nav aria-label={ariaLabel}>
<RouterProvider navigate={(to) => router.push(to)}>
<Container size={maxWidth} className={styles.bar()}>
{children}
</Container>
</RouterProvider>
</nav>
</header>
</NavbarProvider>
);
}
export interface NavbarContentProps {
/** Where the group sits: at the start, in the middle, or at the end. */
justify?: "start" | "center" | "end";
/** Hide the group when the navbar is collapsed. Use it for the links that move into the menu. */
isCollapsible?: boolean;
className?: string;
children?: ReactNode;
}
const justifyClasses = {
// Start and end share the free space equally, so the middle group is
// truly centered.
start: "flex-1 basis-0 justify-start",
center: "shrink-0 justify-center",
end: "flex-1 basis-0 justify-end",
} as const;
/**
* A group of things in the bar. Use up to three: one at the start, one in the
* middle and one at the end.
*/
export function NavbarContent({
justify = "start",
isCollapsible = false,
className,
children,
}: NavbarContentProps) {
const { collapse } = useNavbar();
return (
<div
className={cn(
"items-center gap-1",
isCollapsible ? showWhenExpanded[collapse] : "flex",
justifyClasses[justify],
className,
)}
>
{children}
</div>
);
}
export interface NavbarBrandProps {
/** Make the brand a link, usually to the home page. */
href?: ComponentProps<typeof Link>["href"];
className?: string;
children?: ReactNode;
}
/** The name or logo of the site, at the start of the bar. */
export function NavbarBrand({ href, className, children }: NavbarBrandProps) {
const classes = cn(navbarStyles().brand(), className);
if (href !== undefined) {
return (
<Link href={href} className={classes}>
{children}
</Link>
);
}
return <div className={classes}>{children}</div>;
}
interface NavbarItemShared {
/** The page or section the user is on. Highlights the item and marks it as the current page. */
isActive?: boolean;
className?: string;
children?: ReactNode;
}
/** Rendered as a link (`next/link`). */
export interface NavbarItemLinkProps
extends NavbarItemShared,
Omit<ComponentProps<typeof Link>, "className" | "children"> {}
/** Rendered as a `<button>`, for an action instead of a page. */
export interface NavbarItemButtonProps
extends NavbarItemShared,
Omit<ComponentPropsWithoutRef<"button">, "className" | "children"> {
href?: undefined;
}
export type NavbarItemProps = NavbarItemLinkProps | NavbarItemButtonProps;
/**
* A link in the bar. Pass `href` for a page, or leave it out for a button that
* runs `onClick`. `isActive` marks the current page.
*/
export function NavbarItem({
isActive = false,
className,
...props
}: NavbarItemProps) {
const classes = cn(navbarStyles().item(), className);
const state = {
"data-active": isActive || undefined,
"aria-current": isActive ? ("page" as const) : undefined,
};
if (props.href !== undefined) {
return <Link {...props} {...state} className={classes} />;
}
return <button type="button" {...props} {...state} className={classes} />;
}
export interface NavbarToggleProps {
/** Accessible names of the button. */
openLabel?: string;
closeLabel?: string;
className?: string;
}
/**
* The button that opens and closes the menu. It is only shown when the navbar
* is collapsed, and tells screen readers whether the menu is open.
*/
export function NavbarToggle({
openLabel = "Open menu",
closeLabel = "Close menu",
className,
}: NavbarToggleProps) {
const { collapse, isMenuOpen, setMenuOpen, menuId, toggleId } = useNavbar();
return (
<Button
id={toggleId}
isIcon
variant="ghost"
size="sm"
aria-label={isMenuOpen ? closeLabel : openLabel}
aria-expanded={isMenuOpen}
aria-controls={menuId}
className={cn(showWhenCollapsed[collapse], className)}
onPress={() => setMenuOpen(!isMenuOpen)}
>
{isMenuOpen ? <XIcon /> : <MenuIcon />}
</Button>
);
}
export interface NavbarMenuProps {
className?: string;
children?: ReactNode;
}
/**
* The links of a collapsed navbar, as a panel that drops down under the bar.
* It is only shown when the navbar is collapsed and the menu is open.
*/
export function NavbarMenu({ className, children }: NavbarMenuProps) {
const { collapse, isMenuOpen, menuId } = useNavbar();
const styles = navbarStyles();
return (
<div
id={menuId}
hidden={!isMenuOpen}
className={cn(
styles.menu(),
isMenuOpen ? showWhenCollapsed[collapse] : "",
className,
)}
>
<div className={styles.menuInner()}>{children}</div>
</div>
);
}
/**
* A link in the menu. Like `NavbarItem`, but bigger, and choosing it closes the
* menu.
*/
export function NavbarMenuItem({
isActive = false,
className,
onClick,
...props
}: NavbarItemProps) {
const { setMenuOpen } = useNavbar();
const classes = cn(navbarStyles().menuItem(), className);
const state = {
"data-active": isActive || undefined,
"aria-current": isActive ? ("page" as const) : undefined,
};
if (props.href !== undefined) {
return (
<Link
{...props}
{...state}
className={classes}
onClick={(event) => {
(onClick as ComponentProps<typeof Link>["onClick"])?.(event);
setMenuOpen(false);
}}
/>
);
}
return (
<button
type="button"
{...props}
{...state}
className={classes}
onClick={(event) => {
(onClick as ComponentPropsWithoutRef<"button">["onClick"])?.(event);
setMenuOpen(false);
}}
/>
);
}
export interface NavbarMenuSectionProps {
/** A small heading above the items. */
title?: ReactNode;
className?: string;
children?: ReactNode;
}
/**
* A titled group of items in the menu. Use it to bring the entries of a
* dropdown or a mega menu into the mobile menu, where they are listed flat.
*/
export function NavbarMenuSection({
title,
className,
children,
}: NavbarMenuSectionProps) {
return (
<div className={cn("flex flex-col gap-1 pt-2", className)}>
{title ? <p className={navbarStyles().sectionTitle()}>{title}</p> : null}
{children}
</div>
);
}It imports MenuIcon and XIcon from @/components/icons for the toggle. Add those icons, or swap them for your own.
4. Add the dropdown file (optional)
The dropdown menu and the mega menu live in their own file, so a navbar without them does not need it. It uses ChevronDownIcon and Container, and the popover styles from globals.css: copy the popover-in keyframes and the .popover[data-entering] rule, or the lists appear without their small fade.
src/components/ui/navbar/navbar-dropdown.tsxShow code
"use client";
import Link from "next/link";
import {
type ComponentProps,
type ReactNode,
useCallback,
useContext,
useEffect,
useId,
useRef,
useState,
} from "react";
import {
Button as AriaButton,
Dialog,
DialogTrigger,
Menu,
MenuItem,
type MenuItemProps,
MenuTrigger,
OverlayTriggerStateContext,
Popover,
Text,
} from "react-aria-components";
import { ChevronDownIcon } from "@/components/icons";
import { Container } from "@/components/ui/container/container";
import { cn } from "@/lib/cn";
import { cx } from "@/lib/primitive";
import { useNavbar } from "@/types/navbar-context";
import { navbarStyles } from "@/types/navbar-styles";
interface TriggerProps {
/** What the button shows. A string also names the menu for screen readers. */
label: ReactNode;
/** The section the user is in. Highlights the button like an active item. */
isActive?: boolean;
/**
* Open the menu when the pointer is over the button, and close it when the
* pointer leaves. Clicking the button then keeps the menu open until it is
* dismissed. On touch screens the menu still opens on tap, and the keyboard
* works as usual.
*/
isHover?: boolean;
className?: string;
children?: ReactNode;
}
// How long the pointer may be away from both the button and the panel before
// a hover menu closes. It bridges the gap between them.
const closeDelay = 150;
// Sent when a menu opens on hover, so the others in the page close: two menus
// should never be open at once.
const menuOpenEvent = "navbar-menu-open";
// The state of a menu that can also open on hover. It is always controlled, so
// the same code serves both modes.
function useHoverMenu(isHover: boolean) {
const [isOpen, setOpen] = useState(false);
// Whether the menu was opened by hover (and so closes by hover), and not by
// a click or the keyboard.
const [isHoverOpened, setHoverOpened] = useState(false);
const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
const id = useId();
const wrapRef = useRef<HTMLSpanElement>(null);
const panelRef = useRef<HTMLDivElement>(null);
const cancelClose = useCallback(() => {
if (timer.current) clearTimeout(timer.current);
timer.current = undefined;
}, []);
const scheduleClose = () => {
if (!isHover || !isHoverOpened) return;
cancelClose();
timer.current = setTimeout(() => {
setOpen(false);
setHoverOpened(false);
}, closeDelay);
};
useEffect(() => cancelClose, [cancelClose]);
useEffect(() => {
const closeForOther = (event: Event) => {
if ((event as CustomEvent<string>).detail === id) return;
cancelClose();
setOpen(false);
setHoverOpened(false);
};
document.addEventListener(menuOpenEvent, closeForOther);
return () => document.removeEventListener(menuOpenEvent, closeForOther);
}, [id, cancelClose]);
// A non-modal popover, which hover menus use so the page underneath stays
// usable, is not closed by a click outside of it. Do that here.
useEffect(() => {
if (!isHover || !isOpen) return;
const closeOnOutsidePress = (event: PointerEvent) => {
const target = event.target as Node;
if (wrapRef.current?.contains(target)) return;
if (panelRef.current?.contains(target)) return;
cancelClose();
setOpen(false);
setHoverOpened(false);
};
document.addEventListener("pointerdown", closeOnOutsidePress, true);
return () =>
document.removeEventListener("pointerdown", closeOnOutsidePress, true);
}, [isHover, isOpen, cancelClose]);
return {
isOpen,
// Hover-opened menus must not take the focus away from what the user is doing.
isHoverOpened,
onOpenChange(next: boolean) {
cancelClose();
setOpen(next);
setHoverOpened(false);
},
// Handlers for the button.
triggerProps: {
onHoverStart() {
if (!isHover) return;
cancelClose();
document.dispatchEvent(new CustomEvent(menuOpenEvent, { detail: id }));
if (!isOpen) setHoverOpened(true);
setOpen(true);
},
onHoverEnd: scheduleClose,
},
// Pressing the button while hover has it open pins it: from then on the
// pointer leaving does not close it. Only Escape, a click outside or a
// choice does.
onPointerDownCapture() {
cancelClose();
setHoverOpened(false);
},
// The button's wrapper, so a press on the button is not an outside press.
wrapRef,
// Handlers for the panel: being over it keeps the menu open.
panelProps: {
ref: panelRef,
onPointerEnter(event: React.PointerEvent) {
if (isHover && event.pointerType === "mouse") cancelClose();
},
onPointerLeave(event: React.PointerEvent) {
if (event.pointerType === "mouse") scheduleClose();
},
},
};
}
// Both menus open from a button that looks like a NavbarItem, with a chevron.
function Trigger({
label,
isActive,
className,
...props
}: Pick<TriggerProps, "label" | "isActive" | "className"> &
ReturnType<typeof useHoverMenu>["triggerProps"]) {
const styles = navbarStyles();
return (
<AriaButton
{...props}
data-active={isActive || undefined}
className={cn(styles.item(), styles.trigger(), className)}
>
{label}
<ChevronDownIcon className={styles.chevron()} />
</AriaButton>
);
}
export type NavbarDropdownProps = TriggerProps;
/**
* A button in the bar that opens a short list of links or actions. It is a
* react-aria Menu, so the arrow keys move between the items, typing jumps to
* one, Enter chooses it, and Escape closes the list.
*
* Use it for a handful of related entries. For a lot of links, or links that
* need a description, use `NavbarMegaMenu`.
*
* @example
* <NavbarDropdown label="Products">
* <NavbarDropdownItem href="/pricing">Pricing</NavbarDropdownItem>
* <NavbarDropdownItem onAction={signOut}>Sign out</NavbarDropdownItem>
* </NavbarDropdown>
*/
export function NavbarDropdown({
label,
isActive,
isHover = false,
className,
children,
}: NavbarDropdownProps) {
const styles = navbarStyles();
const menu = useHoverMenu(isHover);
return (
<MenuTrigger isOpen={menu.isOpen} onOpenChange={menu.onOpenChange}>
{/* `contents` keeps the wrapper out of the layout: it only sees the press. */}
<span
ref={menu.wrapRef}
className="contents"
onPointerDownCapture={menu.onPointerDownCapture}
>
<Trigger
label={label}
isActive={isActive}
className={className}
{...menu.triggerProps}
/>
</span>
<Popover
placement="bottom start"
offset={8}
// A modal popover puts an invisible layer over the page, which would
// count as the pointer leaving the button.
isNonModal={isHover}
className={styles.dropdown()}
>
<div className="p-1" {...menu.panelProps}>
<Menu
autoFocus={menu.isHoverOpened ? false : undefined}
className="flex flex-col outline-none"
>
{children}
</Menu>
</div>
</Popover>
</MenuTrigger>
);
}
export interface NavbarDropdownItemProps
extends Omit<MenuItemProps, "className" | "children"> {
/** An icon before the label. */
icon?: ReactNode;
/** A smaller line under the label. */
description?: ReactNode;
className?: string;
children?: ReactNode;
}
/**
* One entry of a `NavbarDropdown`. Give it an `href` to link to a page, or
* `onAction` to run something. Give it a `textValue` when its children are
* not plain text, so typing can jump to it.
*/
export function NavbarDropdownItem({
icon,
description,
className,
children,
textValue,
...props
}: NavbarDropdownItemProps) {
return (
<MenuItem
{...props}
textValue={
textValue ?? (typeof children === "string" ? children : undefined)
}
className={cx(navbarStyles().dropdownItem(), className)}
>
{icon ? (
<span className="mt-0.5 shrink-0 text-muted-fg [&_svg]:size-4">
{icon}
</span>
) : null}
<span className="flex min-w-0 flex-col">
<Text slot="label">{children}</Text>
{description ? (
<Text slot="description" className="text-xs text-muted-fg">
{description}
</Text>
) : null}
</span>
</MenuItem>
);
}
export interface NavbarMegaMenuProps extends TriggerProps {
/** How many columns the panel has. Each `NavbarMegaMenuSection` is one. */
columns?: 1 | 2 | 3 | 4;
}
const columnClasses = {
1: "grid-cols-1",
2: "grid-cols-1 sm:grid-cols-2",
3: "grid-cols-1 sm:grid-cols-2 lg:grid-cols-3",
4: "grid-cols-1 sm:grid-cols-2 lg:grid-cols-4",
} as const;
/**
* A button in the bar that opens a wide panel under it, as wide as the bar,
* for many links grouped in sections. The panel is a react-aria Dialog: focus
* moves into it, Tab walks through its links, and Escape or a click outside
* closes it.
*
* @example
* <NavbarMegaMenu label="Components" columns={3}>
* <NavbarMegaMenuSection title="Forms">
* <NavbarMegaMenuLink href="/select" description="Pick one option">
* Select
* </NavbarMegaMenuLink>
* </NavbarMegaMenuSection>
* </NavbarMegaMenu>
*/
export function NavbarMegaMenu({
label,
isActive,
isHover = false,
columns = 3,
className,
children,
}: NavbarMegaMenuProps) {
const { barRef, maxWidth } = useNavbar();
const styles = navbarStyles();
const menu = useHoverMenu(isHover);
return (
<DialogTrigger isOpen={menu.isOpen} onOpenChange={menu.onOpenChange}>
<span
ref={menu.wrapRef}
className="contents"
onPointerDownCapture={menu.onPointerDownCapture}
>
<Trigger label={label} isActive={isActive} {...menu.triggerProps} />
</span>
{/* Anchored to the bar, not to the button, so it opens flush under the
bar and as wide as it. */}
<Popover
triggerRef={barRef}
placement="bottom"
offset={0}
shouldFlip={false}
isNonModal={isHover}
className={styles.megaPopover()}
>
<Dialog
aria-label={typeof label === "string" ? label : "Menu"}
className="outline-none"
>
<div {...menu.panelProps}>
<Container
size={maxWidth}
className={cn(
"grid gap-x-8 gap-y-6 py-6",
columnClasses[columns],
className,
)}
>
{children}
</Container>
</div>
</Dialog>
</Popover>
</DialogTrigger>
);
}
export interface NavbarMegaMenuSectionProps {
/** A small heading above the links. */
title?: ReactNode;
className?: string;
children?: ReactNode;
}
/** A column of a mega menu: a heading and the links under it. */
export function NavbarMegaMenuSection({
title,
className,
children,
}: NavbarMegaMenuSectionProps) {
return (
<div className={cn("flex flex-col gap-1", className)}>
{title ? (
<h3 className={navbarStyles().sectionTitle()}>{title}</h3>
) : null}
{children}
</div>
);
}
export interface NavbarMegaMenuLinkProps
extends Omit<ComponentProps<typeof Link>, "className" | "children"> {
/** An icon in a small box before the label. */
icon?: ReactNode;
/** A smaller line under the label. */
description?: ReactNode;
className?: string;
children?: ReactNode;
}
/** A link in a mega menu. Choosing it closes the panel. */
export function NavbarMegaMenuLink({
icon,
description,
className,
children,
onClick,
...props
}: NavbarMegaMenuLinkProps) {
const state = useContext(OverlayTriggerStateContext);
return (
<Link
{...props}
onClick={(event) => {
onClick?.(event);
state?.close();
}}
className={cn(navbarStyles().megaLink(), className)}
>
{icon ? (
<span className="flex size-9 shrink-0 items-center justify-center rounded-lg border bg-bg text-muted-fg [&_svg]:size-4">
{icon}
</span>
) : null}
<span className="flex min-w-0 flex-col">
<span className="font-medium">{children}</span>
{description ? (
<span className="text-muted-fg">{description}</span>
) : null}
</span>
</Link>
);
}5. Use it
import {
Navbar,
NavbarBrand,
NavbarContent,
NavbarItem,
NavbarMenu,
NavbarMenuItem,
NavbarMenuSection,
NavbarToggle,
} from "@/components/ui/navbar/navbar";
// Only if you use a dropdown or a mega menu:
import {
NavbarDropdown,
NavbarDropdownItem,
NavbarMegaMenu,
NavbarMegaMenuLink,
NavbarMegaMenuSection,
} from "@/components/ui/navbar/navbar-dropdown";Anatomy
A navbar is a row of up to three groups, plus a menu for small screens.
<Navbar>
<NavbarContent>
<NavbarToggle />
<NavbarBrand href="/">centerUI</NavbarBrand>
</NavbarContent>
<NavbarContent isCollapsible justify="center">
<NavbarItem href="/docs" isActive>Docs</NavbarItem>
<NavbarItem href="/components">Components</NavbarItem>
</NavbarContent>
<NavbarContent justify="end">
<Button size="sm">Sign in</Button>
</NavbarContent>
<NavbarMenu>
<NavbarMenuItem href="/docs" isActive>Docs</NavbarMenuItem>
<NavbarMenuItem href="/components">Components</NavbarMenuItem>
</NavbarMenu>
</Navbar>| Part | Rendered as | Notes |
|---|---|---|
| Navbar | header > nav | The bar. Holds the groups in a Container, and owns whether the menu is open. |
| NavbarContent | div | A group of things: one at the start, one in the middle, one at the end. |
| NavbarBrand | a or div | The name or logo of the site. |
| NavbarItem | a or button | A link in the bar. Highlighted when it is the current page. |
| NavbarToggle | Button | Opens and closes the menu. Only shown when the navbar is collapsed. |
| NavbarMenu | div | The panel that drops down under the bar with the links of a collapsed navbar. |
| NavbarMenuItem | a or button | A link in the menu. Choosing it closes the menu. |
| NavbarMenuSection | div | A titled group of items in the menu, for the entries of a dropdown or mega menu. |
| NavbarDropdown | Button + Menu | A button that opens a short list of links or actions, with keyboard navigation. |
| NavbarMegaMenu | Button + Dialog | A button that opens a panel as wide as the bar, with many links in sections. |
The start and end groups share the free space equally, so a group set to center is truly in the middle of the bar. Mark the group of links with isCollapsible so it is hidden when the menu takes over.
Examples
Live previews with code you can copy. A navbar in a preview does not stick to the top, so the sticky example is code only.
Usage
Below the md breakpoint the links fold into the menu and the toggle button appears. Resize the window to see it.
Active link
isActive highlights the item and sets aria-current=“page”. Usually you compute it from the current path. Here it follows the item you click.
Open on hover
Set isHover on a dropdown or a mega menu to open it when the pointer is over its button, and close it when the pointer leaves. The pointer can cross the small gap to the panel, and stay in it, without closing it.
Move the pointer over a menu.
- Clicking the button while the menu is open from hover keeps it open, until Escape, a click outside or a choice closes it.
- Touch screens have no hover: a tap opens the menu as usual. Keyboard users open it with Enter or Space, and the focus moves into the menu. A menu opened by hover does not take the focus.
- Hover menus are a convenience, not the only way in. Keep the entries reachable by click and keyboard too, which isHover does not change.
Collapse point
collapse decides where the links fold into the menu. It uses Tailwind breakpoints, so it follows the width of the screen.
| Value | Menu shown | Use it |
|---|---|---|
| sm | below 640px | Fold only on the smallest phones |
| md (default) | below 768px | Fold on phones, keep the links on tablets and up |
| lg | below 1024px | Fold on tablets too, for a long list of links |
| always | at every width | Always a menu, with the toggle always shown |
| never | at no width | Links always in the bar, no toggle |
{/* Links fold into the menu below the md breakpoint (the default) */}
<Navbar collapse="md">…</Navbar>
{/* Fold earlier or later */}
<Navbar collapse="sm">…</Navbar>
<Navbar collapse="lg">…</Navbar>
{/* Always a menu, or never */}
<Navbar collapse="always">…</Navbar>
<Navbar collapse="never">…</Navbar>Sticky
isSticky keeps the bar at the top of the screen while the page scrolls. It sits above the content, so give the page a normal top margin.
{/* Stays at the top of the screen while the page scrolls */}
<Navbar isSticky>…</Navbar>Bordered and blurred
By default there is a line under the bar and the background is translucent, blurring what scrolls under it. Turn either off for a flat look.
Sizes
Maximum width
The bar spans the page, but its content stays within maxWidth, which takes the sizes of Container. Match it to the width of your page content.
Component API
Every part takes a className, and the props below.
Navbar
| Prop | Type | Default |
|---|---|---|
| aria-label | string | "Main" |
| isSticky | boolean | false |
| isBordered | boolean | true |
| isBlurred | boolean | true |
| size | "sm" | "md" | "lg" | "md" |
| maxWidth | "sm" | "md" | "lg" | "xl" | "2xl" | "full" | "xl" |
| collapse | "sm" | "md" | "lg" | "always" | "never" | "md" |
| isMenuOpen | boolean | - |
| defaultMenuOpen | boolean | false |
| onMenuOpenChange | (isOpen: boolean) => void | - |
NavbarContent
| Prop | Type | Default |
|---|---|---|
| justify | "start" | "center" | "end" | "start" |
| isCollapsible | boolean | false |
NavbarBrand
| Prop | Type | Default |
|---|---|---|
| href | string | UrlObject | - |
NavbarItem and NavbarMenuItem
| Prop | Type | Default |
|---|---|---|
| isActive | boolean | false |
| href | string | UrlObject | - (a button without it) |
| onClick | (event) => void | - |
With href they accept every next/link prop, and without it every button attribute.
NavbarToggle
| Prop | Type | Default |
|---|---|---|
| openLabel | string | "Open menu" |
| closeLabel | string | "Close menu" |
NavbarMenu
Takes only className and its children, which are NavbarMenuItem and NavbarMenuSection elements.
NavbarMenuSection
| Prop | Type | Default |
|---|---|---|
| title | ReactNode | - |
NavbarDropdown
| Prop | Type | Default |
|---|---|---|
| label | ReactNode | - (required) |
| isActive | boolean | false |
| isHover | boolean | false |
NavbarDropdownItem
| Prop | Type | Default |
|---|---|---|
| href | string | - |
| onAction | () => void | - |
| icon | ReactNode | - |
| description | ReactNode | - |
| textValue | string | the text children |
| isDisabled | boolean | false |
It accepts everything the react-aria MenuItem does. A link is a client-side navigation, like the ones in the bar.
NavbarMegaMenu
| Prop | Type | Default |
|---|---|---|
| label | ReactNode | - (required) |
| isActive | boolean | false |
| isHover | boolean | false |
| columns | 1 | 2 | 3 | 4 | 3 |
NavbarMegaMenuSection
| Prop | Type | Default |
|---|---|---|
| title | ReactNode | - |
NavbarMegaMenuLink
| Prop | Type | Default |
|---|---|---|
| href | string | UrlObject | - (required) |
| icon | ReactNode | - |
| description | ReactNode | - |
| onClick | (event) => void | - |
It accepts every next/link prop.