Components
Button
Triggers an action. Built on react-aria-components, so it handles mouse, touch, keyboard and screen readers consistently.
Introduction
Button triggers an action or, when you pass href, navigates to a page. It is built on the Button of react-aria-components, so press, hover, keyboard focus and disabled states behave the same with a mouse, a finger, a keyboard and a screen reader.
- Five variants and nine sizes, from
xxsto4xl. - Icon-only buttons with
isIcon, and icons next to a label. - A link mode that navigates on the client with next/link.
- Eight optional effects, such as
isRippleandisRainbow. - A larger tap area on touch screens.
Installation
centerUI has no CLI or registry yet: components are copied into your project. Start by installing what Button depends on.
# 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 clsxButton expects React 19, Tailwind CSS v4 and Next.js (the link mode uses next/link). Then add the source files as described in Manual installation.
Manual installation
Copy these files into your project and keep the paths, or adjust the imports. The @/ alias must point to src/.
1. Add the class helpers
src/lib/cn.tsShow code
import { type ClassValue, clsx } from "clsx";
import { twMerge } from "tailwind-merge";
/**
* Joins class values and resolves Tailwind conflicts (the last one wins).
* Safe to use in Server and Client Components. For react-aria-components,
* whose `className` can be a function, use `cx` from `@/lib/primitive`.
*
* @example
* <div className={cn("p-2", isActive && "bg-muted", className)} />
*/
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}src/lib/primitive.tsShow code
import type { ClassValue } from "clsx";
import { composeRenderProps } from "react-aria-components";
import { cn } from "./cn";
// This module imports react-aria-components, which creates React contexts when
// it loads. Import it only from Client Components ("use client"). Server
// Components must use `cn` from "@/lib/cn" instead.
type RenderClassName<T> = string | ((values: T) => string) | undefined;
/**
* Same as `cn`, but for react-aria-components, whose `className` may be a
* string or a function of the render props (`isPressed`, `isFocusVisible`...).
* The last argument is the consumer's `className`; everything before it is
* the base classes.
*
* @example
* <AriaButton className={cx("px-3 py-2", className)} />
*/
export function cx<T = unknown>(
...args: [...ClassValue[], RenderClassName<T>]
): string | ((values: T) => string) {
const className = args.pop() as RenderClassName<T>;
const base = args as ClassValue[];
return composeRenderProps(className, (resolved) => cn(base, resolved));
}2. Add the Button files
src/types/button-styles.tsShow code
import { tv } from "tailwind-variants";
// Kept out of button.tsx (a Client Component) so Server Components can call it
// to style links like buttons.
export const buttonStyles = tv({
base: [
"group relative isolate inline-flex shrink-0 cursor-pointer items-center justify-center gap-2 whitespace-nowrap rounded-md font-medium",
"transition-colors outline-none",
"focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-bg",
"data-disabled:pointer-events-none data-disabled:opacity-50",
"data-pending:cursor-progress data-pending:opacity-70",
"[&_svg]:pointer-events-none [&_svg]:shrink-0",
// Touch hitbox: on touch screens (coarse pointer) an invisible box grows
// the tappable area to at least 44x44px, without changing the layout.
"after:absolute after:top-1/2 after:left-1/2 after:size-[max(100%,2.75rem)] after:-translate-x-1/2 after:-translate-y-1/2 pointer-fine:after:hidden",
],
variants: {
variant: {
primary:
"[--divider:var(--primary-fg)] [--fx:var(--primary)] bg-primary text-primary-fg data-hovered:bg-primary/90 data-pressed:bg-primary/80 hover:bg-primary/90",
secondary:
"[--divider:var(--fg)] [--fx:var(--muted-fg)] bg-secondary text-secondary-fg data-hovered:bg-secondary/80 data-pressed:bg-secondary/60 hover:bg-secondary/80",
outline:
"[--fx:var(--fg)] border bg-transparent text-fg data-hovered:bg-muted data-pressed:bg-muted/70 hover:bg-muted",
ghost:
"[--fx:var(--fg)] text-fg data-hovered:bg-muted data-pressed:bg-muted/70 hover:bg-muted",
danger:
"[--divider:var(--danger-fg)] [--fx:var(--danger)] bg-danger text-danger-fg data-hovered:bg-danger/90 data-pressed:bg-danger/80 hover:bg-danger/90",
},
// Height, padding, text, gap, icon size and radius grow together.
size: {
xxs: "h-5 gap-1 px-1.5 text-[10px] [&_svg]:size-3",
xs: "h-6 gap-1.5 px-2 text-xs [&_svg]:size-3.5",
sm: "h-8 px-3 text-sm [&_svg]:size-4",
md: "h-9 px-4 text-sm [&_svg]:size-4",
lg: "h-11 px-6 text-base [&_svg]:size-5",
xl: "h-12 rounded-lg px-7 text-lg [&_svg]:size-5",
"2xl": "h-14 gap-2.5 rounded-lg px-8 text-xl [&_svg]:size-6",
"3xl": "h-16 gap-3 rounded-xl px-10 text-2xl [&_svg]:size-7",
"4xl": "h-20 gap-4 rounded-xl px-12 text-3xl [&_svg]:size-8",
icon: "size-9 [&_svg]:size-4",
},
// Square button for an icon on its own: same height as its size, and the
// width follows. Give it an accessible name (`aria-label`).
isIcon: {
true: "px-0",
false: "",
},
// Fully round: a circle for an icon on its own, a pill for a button with
// text. It is after `size` so it wins over the larger sizes' own radius.
isCircle: {
true: "rounded-full",
false: "",
},
},
compoundVariants: [
{ isIcon: true, size: "xxs", class: "size-5" },
{ isIcon: true, size: "xs", class: "size-6" },
{ isIcon: true, size: "sm", class: "size-8" },
{ isIcon: true, size: "md", class: "size-9" },
{ isIcon: true, size: "lg", class: "size-11" },
{ isIcon: true, size: "xl", class: "size-12" },
{ isIcon: true, size: "2xl", class: "size-14" },
{ isIcon: true, size: "3xl", class: "size-16" },
{ isIcon: true, size: "4xl", class: "size-20" },
],
defaultVariants: {
variant: "primary",
size: "md",
isIcon: false,
isCircle: false,
},
});src/types/use-ripples.tsShow code
import { useRef, useState } from "react";
import type { Ripple } from "@/components/ui/button/button-effects";
// Matches the fx-ripple animation length in globals.css (650ms) plus a margin.
const RIPPLE_DURATION_MS = 700;
/** State for the ripples of one button. Does nothing unless `enabled`. */
export function useRipples(enabled: boolean | undefined) {
const [ripples, setRipples] = useState<Ripple[]>([]);
const nextId = useRef(0);
function add(rect: DOMRect, x: number, y: number) {
const size =
2 * Math.hypot(Math.max(x, rect.width - x), Math.max(y, rect.height - y));
const id = nextId.current++;
setRipples((current) => [...current, { id, x, y, size }]);
// Timer instead of onAnimationEnd: it still cleans up if animations are
// disabled or the tab is hidden, so ripples can never pile up.
setTimeout(() => {
setRipples((current) => current.filter((ripple) => ripple.id !== id));
}, RIPPLE_DURATION_MS);
}
return {
ripples,
/** Starts a ripple at the pointer position. */
fromPointer(event: {
clientX: number;
clientY: number;
currentTarget: Element;
}) {
if (!enabled) return;
const rect = event.currentTarget.getBoundingClientRect();
add(rect, event.clientX - rect.left, event.clientY - rect.top);
},
/** Starts a ripple from the center, for presses without a position. */
fromCenter(element: Element) {
if (!enabled) return;
const rect = element.getBoundingClientRect();
add(rect, rect.width / 2, rect.height / 2);
},
};
}src/components/ui/button/button-effects.tsxShow code
import type { ReactNode } from "react";
import { ArrowRightIcon } from "@/components/icons";
import { cn } from "@/lib/cn";
export interface ButtonEffectProps {
/** A light beam travels around the border. */
isBeam?: boolean;
/** A multicolor gradient slides along the border. */
isShine?: boolean;
/** A glint sweeps across the button surface. */
isShiny?: boolean;
/** A ring pulses outward from the button. */
isPulsating?: boolean;
/** On hover a dot expands to fill the button and an arrow slides in. */
isInteractive?: boolean;
/** A ripple spreads from the point of the press. */
isRipple?: boolean;
/** A soft highlight sweeps across the label. */
isShimmer?: boolean;
/** An animated rainbow gradient with a glow underneath. */
isRainbow?: boolean;
}
export type Ripple = { id: number; x: number; y: number; size: number };
/** Separates the effect props from the rest, so they never reach the DOM. */
export function splitEffectProps<T extends ButtonEffectProps>(props: T) {
const {
isBeam,
isShine,
isShiny,
isPulsating,
isInteractive,
isRipple,
isShimmer,
isRainbow,
...rest
} = props;
const fx: ButtonEffectProps = {
isBeam,
isShine,
isShiny,
isPulsating,
isInteractive,
isRipple,
isShimmer,
isRainbow,
};
return { fx, rest };
}
export function hasEffect(fx: ButtonEffectProps) {
return Object.values(fx).some(Boolean);
}
/**
* Wraps the label with the decorative layers for every enabled effect.
* Layers are aria-hidden and ignore the pointer, so they never change how the
* button behaves or is announced.
*/
export function ButtonEffects({
fx,
ripples,
children,
}: {
fx: ButtonEffectProps;
ripples: Ripple[];
children: ReactNode;
}) {
const layer = "pointer-events-none absolute inset-0";
return (
<>
{fx.isRainbow ? (
<span
aria-hidden="true"
className={cn(layer, "fx-rainbow-glow -z-10 rounded-[inherit]")}
/>
) : null}
{fx.isPulsating ? (
<span
aria-hidden="true"
className={cn(layer, "fx-pulse rounded-[inherit]")}
/>
) : null}
<span
aria-hidden="true"
className={cn(layer, "overflow-hidden rounded-[inherit]")}
>
{fx.isRainbow ? <span className={cn(layer, "fx-rainbow")} /> : null}
{fx.isShiny ? <span className={cn(layer, "fx-shiny")} /> : null}
{fx.isInteractive ? (
<span className="absolute top-1/2 left-4 size-2 -translate-y-1/2 scale-100 rounded-full bg-current opacity-20 transition-transform duration-500 ease-out group-data-hovered:scale-[50] group-hover:scale-[50] motion-reduce:transition-none" />
) : null}
{ripples.map((ripple) => (
<span
key={ripple.id}
className="fx-ripple absolute rounded-full bg-current"
style={{
width: ripple.size,
height: ripple.size,
left: ripple.x - ripple.size / 2,
top: ripple.y - ripple.size / 2,
}}
/>
))}
</span>
{fx.isShine ? (
<span
aria-hidden="true"
className={cn(layer, "fx-ring fx-shine rounded-[inherit]")}
/>
) : null}
{fx.isBeam ? (
<span
aria-hidden="true"
className={cn(layer, "fx-ring fx-beam rounded-[inherit]")}
/>
) : null}
<span
className={cn(
"relative z-10 inline-flex items-center gap-[inherit]",
fx.isShimmer && "fx-shimmer",
fx.isInteractive &&
"transition-transform duration-300 group-data-hovered:translate-x-1 group-hover:translate-x-1 motion-reduce:transition-none",
)}
>
{children}
{fx.isInteractive ? (
<span
aria-hidden="true"
className="-ml-2 inline-flex w-0 overflow-hidden opacity-0 transition-all duration-300 group-data-hovered:ml-0 group-hover:ml-0 group-data-hovered:w-4 group-hover:w-4 group-data-hovered:opacity-100 group-hover:opacity-100 motion-reduce:transition-none"
>
<ArrowRightIcon />
</span>
) : null}
</span>
</>
);
}src/components/ui/button/button.tsxShow code
"use client";
import Link from "next/link";
import { type ComponentProps, type ReactNode, useState } from "react";
import {
Button as AriaButton,
type ButtonProps as AriaButtonProps,
composeRenderProps,
} from "react-aria-components";
import type { VariantProps } from "tailwind-variants";
import { Loader } from "@/components/ui/loader/loader";
import { cn } from "@/lib/cn";
import { cx } from "@/lib/primitive";
import { useButtonGroup } from "@/types/button-group-context";
import { buttonStyles } from "@/types/button-styles";
import { useRipples } from "@/types/use-ripples";
import {
type ButtonEffectProps,
ButtonEffects,
hasEffect,
splitEffectProps,
} from "./button-effects";
type StyleProps = VariantProps<typeof buttonStyles> & ButtonEffectProps;
/** Rendered as a `<button>`. */
export interface ButtonProps extends AriaButtonProps, StyleProps {
href?: undefined;
}
/** Rendered as a link (`next/link`) that looks and animates like a button. */
export interface ButtonLinkProps
extends StyleProps,
Omit<ComponentProps<typeof Link>, "className" | "children"> {
className?: string;
children?: ReactNode;
}
type LoaderSize = "xs" | "sm" | "md" | "lg" | "xl";
// The loader that goes with each button size.
const loaderSizes: Record<string, LoaderSize> = {
xxs: "xs",
xs: "xs",
sm: "xs",
md: "sm",
icon: "sm",
lg: "md",
xl: "md",
"2xl": "lg",
"3xl": "lg",
"4xl": "xl",
};
// While the button is pending a loader goes before the label, which stays. An
// icon-only button has no label, so the loader takes the place of its icon.
function ButtonContent({
isPending,
isIcon,
size,
children,
}: {
isPending: boolean;
isIcon: boolean;
size: string;
children: ReactNode;
}) {
if (!isPending) return children;
return (
<>
<Loader
variant={"spinner"}
size={loaderSizes[size] ?? "sm"}
label={false}
/>
{isIcon ? null : children}
</>
);
}
const rainbowClasses = "text-white [text-shadow:0_1px_2px_oklch(0_0_0/0.4)]";
/**
* A button. Pass `href` to render a link instead, so navigation gets the same
* variants, sizes and effects.
*
* While it is pending it shows a loader before its label and ignores
* presses. Set `isPending` yourself, or return a promise from `onPress` and it
* is pending until the promise settles.
*
* @example
* <Button onPress={save}>Save</Button>
* <Button href="/docs" variant="outline">Read the docs</Button>
* <Button onPress={() => save()}>Save</Button> // pending while save() runs
*/
export function Button(props: ButtonProps | ButtonLinkProps) {
if (props.href !== undefined) {
return <LinkButton {...props} />;
}
return <ActionButton {...props} />;
}
function ActionButton(props: ButtonProps) {
const { fx, rest } = splitEffectProps(props);
const {
className,
variant,
size,
isIcon,
isCircle,
children,
onPointerDown,
onPress,
onPressStart,
isPending,
href: _href,
...ariaProps
} = rest;
const group = useButtonGroup();
// Pending while a promise returned by `onPress` has not settled, unless
// `isPending` says otherwise.
const [isRunning, setRunning] = useState(false);
const pending = isPending ?? isRunning;
const buttonSize = size ?? group?.size ?? "md";
const { ripples, fromPointer, fromCenter } = useRipples(fx.isRipple);
return (
<AriaButton
{...ariaProps}
isDisabled={ariaProps.isDisabled ?? group?.isDisabled}
isPending={pending}
onPress={(event) => {
const result: unknown = onPress?.(event);
if (result instanceof Promise) {
setRunning(true);
const done = () => setRunning(false);
result.then(done, done);
}
}}
onPointerDown={(event) => {
fromPointer(event);
onPointerDown?.(event);
}}
// Pointer presses are handled above (they carry a position). Keyboard
// presses have none, so the ripple starts from the center.
onPressStart={(event) => {
if (event.pointerType === "keyboard") fromCenter(event.target);
onPressStart?.(event);
}}
className={cx(
buttonStyles({
variant: variant ?? group?.variant,
size: size ?? group?.size,
isIcon,
isCircle,
}),
fx.isRainbow && rainbowClasses,
className,
)}
>
{composeRenderProps(children, (children) => {
const content = (
<ButtonContent
isPending={pending}
isIcon={Boolean(isIcon) || buttonSize === "icon"}
size={buttonSize}
>
{children}
</ButtonContent>
);
return hasEffect(fx) ? (
<ButtonEffects fx={fx} ripples={ripples}>
{content}
</ButtonEffects>
) : (
content
);
})}
</AriaButton>
);
}
function LinkButton(props: ButtonLinkProps) {
const { fx, rest } = splitEffectProps(props);
const {
className,
variant,
size,
isIcon,
isCircle,
children,
onPointerDown,
onKeyDown,
...linkProps
} = rest;
const group = useButtonGroup();
const { ripples, fromPointer, fromCenter } = useRipples(fx.isRipple);
return (
<Link
{...linkProps}
onPointerDown={(event) => {
fromPointer(event);
onPointerDown?.(event);
}}
onKeyDown={(event) => {
if (event.key === "Enter") fromCenter(event.currentTarget);
onKeyDown?.(event);
}}
className={cn(
buttonStyles({
variant: variant ?? group?.variant,
size: size ?? group?.size,
isIcon,
isCircle,
}),
fx.isRainbow && rainbowClasses,
className,
)}
>
{hasEffect(fx) ? (
<ButtonEffects fx={fx} ripples={ripples}>
{children}
</ButtonEffects>
) : (
children
)}
</Link>
);
}button-effects.tsx imports ArrowRightIcon from @/components/icons. Add that icon, or swap it for your own.
3. Add the styles
Button reads the design tokens described in Theming and needs the effect styles. In src/app/globals.css copy the :root tokens, the @theme inline block, the @custom-variant dark line, and the block commented Button effects (the --beam-angle property, the fx-* keyframes and classes).
4. Use it
import { Button } from "@/components/ui/button/button";Anatomy
A button is a label, optionally with an icon before or after it.
<Button>
<SearchIcon /> {/* icon: optional, before or after the label */}
Search {/* label */}
</Button>When an effect prop is on, Button also renders decorative layers and wraps the content:
<button> <!-- or <a> when href is set -->
<span aria-hidden="true" /> <!-- effect layers, one per enabled effect -->
<span> <!-- content wrapper, only with an effect -->
<svg /> Search
</span>
</button>| Part | Rendered as | Notes |
|---|---|---|
| Root | button, or a link with href | Carries the variant, size and press states. |
| Icon | svg child | Sized and spaced automatically by size. |
| Label | text child | Optional. Leave it out and set isIcon for an icon-only button. |
| Effect layers | aria-hidden spans | Only rendered when an effect prop is on. They never take clicks. |
Examples
Live previews with code you can copy.
Usage
Variants
Use variant to set the visual emphasis.
Sizes
Icon
Set isIcon for a button that holds only an icon. It becomes square at the height of its size, and the width follows. Always give it an accessible name with aria-label.
Circle
Set isCircle for fully round corners. With isIcon the button is a circle. With text it is a pill, with round ends. It works with every variant, size and effect.
Icon with text
Put an icon before or after the label. The gap and the icon size follow the button size, so there is nothing to style by hand.
States
A disabled button is removed from interaction; a pending button shows a loader before its label, stays focusable, and ignores presses. A button is not pending at first: press the one below to see it.
Pending
Press a button to see it. When onPress returns a promise, the button turns pending on its own: a loader appears before the label, which stays, and presses are ignored until the promise settles. An icon-only button shows the loader in place of its icon. Set isPending yourself when the state is yours.
Effects
Set any of these boolean props to true to turn the effect on. They can be combined, work with every variant and size, and respect prefers-reduced-motion.
Beam
A light beam travels around the border.
Shine
A multicolor gradient slides along the border.
Shiny
A glint sweeps across the surface of the button.
Pulsating
A ring pulses outward, in the color of the variant.
Interactive
On hover a dot fills the button and an arrow slides in.
Ripple
A ripple spreads from the exact point you press.
Shimmer
A soft highlight sweeps across the label.
Rainbow
An animated rainbow gradient with a glow underneath.
Combining effects
As a link
Pass href to render a link instead of a button. It navigates on the client with next/link and keeps every variant, size and effect.
Touch hitbox
The smallest sizes are smaller than a fingertip. On touch screens the tappable area grows to at least 44 × 44px, without changing the layout.
The dashed outline is drawn here only for the demo. In your app the extra area is invisible, and it is turned off for mouse and trackpad pointers (pointer: fine), which do not need it. Buttons that are already 44px or taller are unchanged.
Component API
Button accepts every prop of the react-aria-components Button, or of next/link when href is set, plus the ones below.
| Prop | Type | Default |
|---|---|---|
| variant | "primary" | "secondary" | "outline" | "ghost" | "danger" | "primary" |
| size | "xxs" | "xs" | "sm" | "md" | "lg" | "xl" | "2xl" | "3xl" | "4xl" | "icon" | "md" |
| isIcon | boolean | false |
| isCircle | boolean | false |
| isDisabled | boolean | false |
| isPending | boolean | false |
| isBeam | boolean | false |
| isShine | boolean | false |
| isShiny | boolean | false |
| isPulsating | boolean | false |
| isInteractive | boolean | false |
| isRipple | boolean | false |
| isShimmer | boolean | false |
| isRainbow | boolean | false |
| href | string | UrlObject | - (renders a link when set) |
| onPress | (e: PressEvent) => void | - |
| className | string | (renderProps) => string | - |