Get Started
Components
- Accordion
- Attachment
- Avatar
- Badge
- Breadcrumb
- Button
- Button Group
- Card
- Checkbox
- Code Block
- Collapsible
- Dialog
- Dropdown Menu
- Empty
- Field
- Hover Card
- Input
- Input Group
- Input OTP
- Item
- Label
- Marker
- Message
- Number Flow
- Pagination
- Popover
- Progress
- Radio Group
- Select
- Slider
- Sonner
- Spinner
- Switch
- Tooltip
- Separator
- Sheet
- Tabs
- Textarea
- Toggle
- Toggle Group
- Trace
AI Elements
Libraries
Utilities
Order #4189
StatusShipped
Shipping address
100 Market St, San Francisco
Items
2x Studio Headphones
"use client";
import * as React from "react";
import { getTransition, parseMotion, useReducedMotion } from "@/lib/motion";
import { cn } from "@/lib/utils";
const defaultCollapsibleMotion = "450 cubic-bezier(0.32, 0.72, 0, 1)";
interface CollapsibleContextValue {
contentId: string;
disabled: boolean;
motion: string | undefined;
onOpenChange: (open: boolean) => void;
open: boolean;
triggerId: string;
}
const CollapsibleContext = React.createContext<CollapsibleContextValue | null>(
null
);
function useCollapsibleContext(component: string): CollapsibleContextValue {
const ctx = React.useContext(CollapsibleContext);
if (!ctx) {
throw new Error(`${component} must be used within Collapsible`);
}
return ctx;
}
interface CollapsibleProps
extends Omit<React.ComponentProps<"div">, "onChange"> {
defaultOpen?: boolean;
disabled?: boolean;
motion?: string;
onOpenChange?: (open: boolean) => void;
open?: boolean;
}
function Collapsible({
children,
className,
defaultOpen,
disabled = false,
motion,
onOpenChange,
open: openProp,
...props
}: CollapsibleProps) {
const [uncontrolledOpen, setUncontrolledOpen] = React.useState(
defaultOpen ?? false
);
const isControlled = openProp !== undefined;
const open = isControlled ? openProp : uncontrolledOpen;
const triggerId = React.useId();
const contentId = React.useId();
const setOpen = React.useCallback(
(next: boolean) => {
if (!isControlled) {
setUncontrolledOpen(next);
}
onOpenChange?.(next);
},
[isControlled, onOpenChange]
);
const context = React.useMemo<CollapsibleContextValue>(
() => ({
contentId,
disabled,
motion,
onOpenChange: setOpen,
open,
triggerId,
}),
[contentId, disabled, motion, setOpen, open, triggerId]
);
return (
<CollapsibleContext.Provider value={context}>
<div
className={className}
data-disabled={disabled ? "" : undefined}
data-slot="collapsible"
data-state={open ? "open" : "closed"}
{...props}
>
{children}
</div>
</CollapsibleContext.Provider>
);
}
type CollapsibleTriggerProps = Omit<React.ComponentProps<"button">, "ref"> & {
as?: React.ElementType;
ref?: React.Ref<HTMLButtonElement>;
} & Record<string, unknown>;
function CollapsibleTrigger({
as,
children,
className,
onClick,
ref,
...props
}: CollapsibleTriggerProps) {
const { contentId, disabled, onOpenChange, open, triggerId } =
useCollapsibleContext("CollapsibleTrigger");
const handleClick = (event: React.MouseEvent<HTMLButtonElement>) => {
onClick?.(event);
if (event.defaultPrevented || disabled) {
return;
}
onOpenChange(!open);
};
const finalProps: Record<string, unknown> = {
...props,
"aria-controls": contentId,
"aria-expanded": open,
className: cn(className),
"data-disabled": disabled ? "" : undefined,
"data-slot": "collapsible-trigger",
"data-state": open ? "open" : "closed",
id: triggerId,
onClick: handleClick,
ref,
};
if (!(as || "type" in props)) {
finalProps.type = "button";
finalProps.disabled = disabled;
}
const Comp = as ?? "button";
return <Comp {...finalProps}>{children}</Comp>;
}
interface CollapsibleContentProps extends React.ComponentProps<"div"> {
motion?: string | false;
}
function CollapsibleContent({
children,
className,
motion: localMotion,
style,
...props
}: CollapsibleContentProps) {
const {
contentId,
disabled,
motion: contextMotion,
open,
triggerId,
} = useCollapsibleContext("CollapsibleContent");
const reduce = useReducedMotion();
const motionProp =
localMotion === false ? "off" : (localMotion ?? contextMotion);
const motionValue = motionProp ?? defaultCollapsibleMotion;
const gridStyle: React.CSSProperties = {
display: "grid",
gridTemplateRows: open ? "1fr" : "0fr",
opacity: open ? 1 : 0,
...style,
};
if (reduce) {
gridStyle.transition = "none";
} else {
const transition = getTransition(parseMotion(motionValue));
if (transition) {
gridStyle.transition = transition;
}
}
return (
<div
aria-labelledby={triggerId}
data-disabled={disabled ? "" : undefined}
data-slot="collapsible-content"
data-state={open ? "open" : "closed"}
id={contentId}
role="region"
{...props}
>
<div inert={!open} style={gridStyle}>
<div style={{ minHeight: 0, overflow: "hidden" }}>
<div className={cn(className)}>{children}</div>
</div>
</div>
</div>
);
}
export { Collapsible, CollapsibleContent, CollapsibleTrigger };Collapsible reveals or hides a single panel triggered by a button. It is the primitive behind accordion rows and nested file trees.
Installation
$ bunx --bun frakment add collapsible$ npx frakment add collapsible$ pnpm dlx frakment add collapsible$ yarn dlx frakment add collapsible
Copy and paste the following code into your project.
"use client";
import * as React from "react";
import { getTransition, parseMotion, useReducedMotion } from "@/lib/motion";
import { cn } from "@/lib/utils";
const defaultCollapsibleMotion = "450 cubic-bezier(0.32, 0.72, 0, 1)";
interface CollapsibleContextValue {
contentId: string;
disabled: boolean;
motion: string | undefined;
onOpenChange: (open: boolean) => void;
open: boolean;
triggerId: string;
}
const CollapsibleContext = React.createContext<CollapsibleContextValue | null>(
null
);
function useCollapsibleContext(component: string): CollapsibleContextValue {
const ctx = React.useContext(CollapsibleContext);
if (!ctx) {
throw new Error(`${component} must be used within Collapsible`);
}
return ctx;
}
interface CollapsibleProps
extends Omit<React.ComponentProps<"div">, "onChange"> {
defaultOpen?: boolean;
disabled?: boolean;
motion?: string;
onOpenChange?: (open: boolean) => void;
open?: boolean;
}
function Collapsible({
children,
className,
defaultOpen,
disabled = false,
motion,
onOpenChange,
open: openProp,
...props
}: CollapsibleProps) {
const [uncontrolledOpen, setUncontrolledOpen] = React.useState(
defaultOpen ?? false
);
const isControlled = openProp !== undefined;
const open = isControlled ? openProp : uncontrolledOpen;
const triggerId = React.useId();
const contentId = React.useId();
const setOpen = React.useCallback(
(next: boolean) => {
if (!isControlled) {
setUncontrolledOpen(next);
}
onOpenChange?.(next);
},
[isControlled, onOpenChange]
);
const context = React.useMemo<CollapsibleContextValue>(
() => ({
contentId,
disabled,
motion,
onOpenChange: setOpen,
open,
triggerId,
}),
[contentId, disabled, motion, setOpen, open, triggerId]
);
return (
<CollapsibleContext.Provider value={context}>
<div
className={className}
data-disabled={disabled ? "" : undefined}
data-slot="collapsible"
data-state={open ? "open" : "closed"}
{...props}
>
{children}
</div>
</CollapsibleContext.Provider>
);
}
type CollapsibleTriggerProps = Omit<React.ComponentProps<"button">, "ref"> & {
as?: React.ElementType;
ref?: React.Ref<HTMLButtonElement>;
} & Record<string, unknown>;
function CollapsibleTrigger({
as,
children,
className,
onClick,
ref,
...props
}: CollapsibleTriggerProps) {
const { contentId, disabled, onOpenChange, open, triggerId } =
useCollapsibleContext("CollapsibleTrigger");
const handleClick = (event: React.MouseEvent<HTMLButtonElement>) => {
onClick?.(event);
if (event.defaultPrevented || disabled) {
return;
}
onOpenChange(!open);
};
const finalProps: Record<string, unknown> = {
...props,
"aria-controls": contentId,
"aria-expanded": open,
className: cn(className),
"data-disabled": disabled ? "" : undefined,
"data-slot": "collapsible-trigger",
"data-state": open ? "open" : "closed",
id: triggerId,
onClick: handleClick,
ref,
};
if (!(as || "type" in props)) {
finalProps.type = "button";
finalProps.disabled = disabled;
}
const Comp = as ?? "button";
return <Comp {...finalProps}>{children}</Comp>;
}
interface CollapsibleContentProps extends React.ComponentProps<"div"> {
motion?: string | false;
}
function CollapsibleContent({
children,
className,
motion: localMotion,
style,
...props
}: CollapsibleContentProps) {
const {
contentId,
disabled,
motion: contextMotion,
open,
triggerId,
} = useCollapsibleContext("CollapsibleContent");
const reduce = useReducedMotion();
const motionProp =
localMotion === false ? "off" : (localMotion ?? contextMotion);
const motionValue = motionProp ?? defaultCollapsibleMotion;
const gridStyle: React.CSSProperties = {
display: "grid",
gridTemplateRows: open ? "1fr" : "0fr",
opacity: open ? 1 : 0,
...style,
};
if (reduce) {
gridStyle.transition = "none";
} else {
const transition = getTransition(parseMotion(motionValue));
if (transition) {
gridStyle.transition = transition;
}
}
return (
<div
aria-labelledby={triggerId}
data-disabled={disabled ? "" : undefined}
data-slot="collapsible-content"
data-state={open ? "open" : "closed"}
id={contentId}
role="region"
{...props}
>
<div inert={!open} style={gridStyle}>
<div style={{ minHeight: 0, overflow: "hidden" }}>
<div className={cn(className)}>{children}</div>
</div>
</div>
</div>
);
}
export { Collapsible, CollapsibleContent, CollapsibleTrigger };Update the import paths to match your project setup.
Usage
import {
Collapsible,
CollapsibleContent,
CollapsibleTrigger,
} from "@/components/ui/collapsible";<Collapsible>
<CollapsibleTrigger>Toggle</CollapsibleTrigger>
<CollapsibleContent>Hidden content.</CollapsibleContent>
</Collapsible>Examples
Basic
Pass as on the trigger to render a custom element.
This panel can be expanded or collapsed to reveal additional content.
import { ChevronDownIcon } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import {
Collapsible,
CollapsibleContent,
CollapsibleTrigger,
} from "@/components/ui/collapsible";
export function CollapsibleBasic() {
return (
<Card className="mx-auto w-full max-w-sm">
<CardContent>
<Collapsible className="data-[state=open]:bg-muted rounded-md">
<CollapsibleTrigger
as={Button}
className="w-full justify-between"
variant="ghost"
>
Product details
<ChevronDownIcon className="transition-transform duration-200 group-data-[state=open]:rotate-180" />
</CollapsibleTrigger>
<CollapsibleContent className="flex flex-col items-start gap-2 p-2.5 pt-0 text-sm">
<div>
This panel can be expanded or collapsed to reveal additional
content.
</div>
<Button size="sm">Learn more</Button>
</CollapsibleContent>
</Collapsible>
</CardContent>
</Card>
);
}File tree
Compose nested collapsibles to build a tree.
Explorer
import { ChevronRightIcon, FileIcon, FolderIcon } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader } from "@/components/ui/card";
import {
Collapsible,
CollapsibleContent,
CollapsibleTrigger,
} from "@/components/ui/collapsible";
type FileTreeItem = { name: string } | { name: string; items: FileTreeItem[] };
const TREE: FileTreeItem[] = [
{
items: [
{
items: [
{ name: "button.tsx" },
{ name: "card.tsx" },
{ name: "input.tsx" },
],
name: "ui",
},
{ name: "login-form.tsx" },
],
name: "components",
},
{
items: [{ name: "utils.ts" }, { name: "api.ts" }],
name: "lib",
},
{ name: "app.tsx" },
{ name: "package.json" },
];
function Item({ item }: { item: FileTreeItem }) {
if ("items" in item) {
return (
<Collapsible>
<CollapsibleTrigger
as={Button}
className="group w-full justify-start"
size="sm"
variant="ghost"
>
<ChevronRightIcon className="transition-transform group-data-[state=open]/collapsible:rotate-90" />
<FolderIcon />
{item.name}
</CollapsibleTrigger>
<CollapsibleContent className="mt-1 ml-5">
<div className="flex flex-col gap-1">
{item.items.map((child) => (
<Item item={child} key={child.name} />
))}
</div>
</CollapsibleContent>
</Collapsible>
);
}
return (
<Button
className="text-foreground w-full justify-start gap-2"
size="sm"
variant="link"
>
<FileIcon />
<span>{item.name}</span>
</Button>
);
}
export function CollapsibleFileTree() {
return (
<Card className="mx-auto w-full max-w-[16rem] gap-2" size="sm">
<CardHeader>
<p className="text-sm font-medium">Explorer</p>
</CardHeader>
<CardContent>
<div className="flex flex-col gap-1">
{TREE.map((item) => (
<Item item={item} key={item.name} />
))}
</div>
</CardContent>
</Card>
);
}In context
Details panel
Frakment ships every component as a local file. Update by re-running the CLI and diffing.
import {
Collapsible,
CollapsibleContent,
CollapsibleTrigger,
} from "@/components/ui/collapsible";
export function CollapsibleDetails() {
return (
<Collapsible className="mx-auto w-full max-w-sm">
<CollapsibleTrigger className="text-sm font-medium">
Show details
</CollapsibleTrigger>
<CollapsibleContent className="text-muted-foreground pt-2 text-sm">
Frakment ships every component as a local file. Update by re-running the
CLI and diffing.
</CollapsibleContent>
</Collapsible>
);
}Motion
Collapsible accepts a motion prop on the root, inherited by CollapsibleContent. Pass a per-item override on CollapsibleContent to diverge from the root.
<Collapsible motion="200 ease-out">
<CollapsibleTrigger>Toggle</CollapsibleTrigger>
<CollapsibleContent motion="300 cubic-bezier(0.4, 0, 0.2, 1)">Revealed content.</CollapsibleContent>
</Collapsible>motion accepts "off", "150", "150 ease-out", or "150 cubic-bezier(0.4, 0, 0.2, 1)". The default is a 450ms smooth-out curve. prefers-reduced-motion wins and the reveal is instant.
API Reference
Collapsible
| Prop | Type | Default | Description |
|---|---|---|---|
defaultOpen | boolean | false | Whether the panel starts expanded. |
open | boolean | — | Controlled open state. |
onOpenChange | (open: boolean) => void | — | Called when the panel toggles. |
disabled | boolean | false | Prevent toggling. |
motion | string | — | Motion string for the reveal. Pass off to disable. |
CollapsibleTrigger
| Prop | Type | Default | Description |
|---|---|---|---|
as | React.ElementType | — | Renders a different root element or component. Defaults to button. |
CollapsibleContent
| Prop | Type | Default | Description |
|---|---|---|---|
motion | stringfalse | — | Per-content override for the reveal motion. Pass false to disable. |
Controlled
const [open, setOpen] = React.useState(false);
<Collapsible onOpenChange={setOpen} open={open}>
{/* ... */}
</Collapsible>Keyboard
| Key | Action |
|---|---|
Space / Enter | Toggle the panel |
Data Attributes
| Attribute | Values |
|---|---|
data-slot | collapsible, collapsible-trigger, collapsible-content |
data-state | open | closed |
data-disabled | Present on disabled root, trigger, and content |
Accessibility
- Triggers expose
aria-expandedandaria-controls; content is labeled witharia-labelledbyand carriesrole="region". - Keyboard:
EnterandSpacetoggle the panel. - Provide a descriptive trigger label or
aria-label.
Best Practices
- Use for optional detail. Content that must be visible on load belongs on the page.
- Keep the trigger visible. Never hide the trigger inside the content.
- Default closed for long content. Default open for short, always-relevant blocks.
- Do not nest collapsibles. Two levels is hard to track; use Accordion for nested groups.