# Accordion

A stack of headings that each open and close a section of content.

```tsx
import * as stylex from "@stylexjs/stylex"
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from "@/components/ui/accordion"
import { width } from "@/theme/tokens.stylex"

const styles = stylex.create({
  accordion: { maxWidth: width.lg },
})

export default function AccordionDemo() {
  return (
    <Accordion defaultValue={["drafts"]} xstyle={styles.accordion}>
      <AccordionItem value="drafts">
        <AccordionTrigger>Where are my drafts saved?</AccordionTrigger>
        <AccordionContent>
          Drafts save to your workspace every few seconds. A deleted draft stays in the trash for 30
          days before it is removed.
        </AccordionContent>
      </AccordionItem>
      <AccordionItem value="sharing">
        <AccordionTrigger>Who can see a shared notebook?</AccordionTrigger>
        <AccordionContent>
          Only the people you invite. A link can be view-only or editable, and you can turn it off
          in the notebook&apos;s settings.
        </AccordionContent>
      </AccordionItem>
      <AccordionItem value="offline">
        <AccordionTrigger>Can I work without a connection?</AccordionTrigger>
        <AccordionContent>
          Yes. Edits you make offline stay on the device and sync the next time you connect.
        </AccordionContent>
      </AccordionItem>
    </Accordion>
  )
}
```

## Installation

**Command**

```bash
npx shadcn@latest add @arene/accordion
```

Needs the [arene setup](https://www.arene.style/docs/installation) first.

**Manual**

1. Install the packages it imports:

   ```bash
   npm install @base-ui/react @stylexjs/stylex clsx
   ```

2. Set up the token layer and the StyleX compiler, if you have not already. See
   [Installation](https://www.arene.style/docs/installation), and paste `states.ts` and `state-styles.ts`
   from the same page. The trigger takes its focus ring and its disabled dim from
   the first and reads Base UI's state through the second. The chevron reads the
   trigger's hover and open state through the `accordionTrigger` marker in
   `markers.stylex.ts`, also on that page. `interop.css` sizes any icon you put in
   a trigger.

3. Paste this source into the file named in its title.

   ```tsx title="components/ui/accordion.tsx"
   "use client"

   import type { CSSProperties } from "react"
   import { Accordion as AccordionPrimitive } from "@base-ui/react/accordion"
   import * as stylex from "@stylexjs/stylex"
   import type { StyleXStyles } from "@stylexjs/stylex"
   import { clsx } from "clsx"

   import { stateStyles } from "@/lib/state-styles"
   import { accordionTrigger } from "@/theme/markers.stylex"
   import { states } from "@/theme/states"
   import { color, duration, ease, leading, radius, space, text } from "@/theme/tokens.stylex"

   const styles = stylex.create({
     root: { display: "flex", flexDirection: "column", width: "100%" },
     item: {
       borderBlockEndWidth: { default: 1, ":last-child": 0 },
       borderBlockEndStyle: "solid",
     },
     header: { display: "flex" },
     trigger: {
       display: "flex",
       flexGrow: 1,
       alignItems: "flex-start",
       gap: space.s2,
       textAlign: "start",
       paddingBlock: space.s2_5,
       fontSize: text.sm,
       lineHeight: leading.sm,
       fontWeight: 500,
       borderRadius: radius.lg,
       borderWidth: 1,
       borderStyle: "solid",
       transitionProperty: "border-color, box-shadow",
       transitionDuration: duration.color,
       transitionTimingFunction: ease.standard,
       "--arene-icon-size": space.s4,
     },
     chevron: {
       marginInlineStart: "auto",
       width: space.s5,
       height: space.s5,
       color: {
         default: color.mutedForeground,
         [stylex.when.ancestor(":hover", accordionTrigger)]: color.foreground,
       },
       transitionProperty: "color",
       transitionDuration: duration.color,
       transitionTimingFunction: ease.standard,
     },
     chevronPath: {
       transformBox: "fill-box",
       transformOrigin: "center",
       transform: {
         default: "none",
         [stylex.when.ancestor("[data-panel-open]", accordionTrigger)]: "scaleY(-1)",
       },
       transitionProperty: "transform",
       transitionDuration: { default: duration.move, "@media (prefers-reduced-motion: reduce)": "0s" },
       transitionTimingFunction: ease.standard,
     },
     content: {
       overflow: "hidden",
       height: "var(--accordion-panel-height)",
       fontSize: text.sm,
       lineHeight: leading.sm,
       transitionProperty: "height",
       transitionDuration: {
         default: duration.panel,
         "@media (prefers-reduced-motion: reduce)": "0s",
       },
       transitionTimingFunction: ease.spring,
     },
     contentHidden: { height: 0 },
     contentInner: { paddingBlockEnd: space.s2_5 },
   })

   type Overrides = { xstyle?: StyleXStyles; className?: string }

   type AccordionProps = Omit<AccordionPrimitive.Root.Props, "className"> & Overrides

   function Accordion({ xstyle, className, ...props }: AccordionProps) {
     const sx = stylex.props(styles.root, xstyle)
     return (
       <AccordionPrimitive.Root
         data-slot="accordion"
         {...sx}
         {...props}
         className={clsx(sx.className, className)}
       />
     )
   }

   type AccordionItemProps = Omit<AccordionPrimitive.Item.Props, "className"> & Overrides

   function AccordionItem({ xstyle, className, ...props }: AccordionItemProps) {
     const sx = stylex.props(styles.item, xstyle)
     return (
       <AccordionPrimitive.Item
         data-slot="accordion-item"
         {...sx}
         {...props}
         className={clsx(sx.className, className)}
       />
     )
   }

   type AccordionTriggerProps = Omit<AccordionPrimitive.Trigger.Props, "className" | "style"> &
     Overrides & {
       style?: CSSProperties
       headerProps?: Omit<AccordionPrimitive.Header.Props, "className">
     }

   function AccordionTrigger({
     xstyle,
     style,
     className,
     headerProps,
     children,
     ...props
   }: AccordionTriggerProps) {
     return (
       <AccordionPrimitive.Header
         data-slot="accordion-header"
         {...stylex.props(styles.header)}
         {...headerProps}
       >
         <AccordionPrimitive.Trigger
           data-slot="accordion-trigger"
           {...props}
           {...stateStyles(
             (state) => [
               accordionTrigger,
               styles.trigger,
               states.focusRing,
               state.disabled && states.disabled,
               xstyle,
             ],
             { className, style, hook: "arene-icons" },
           )}
         >
           {children}
           <svg
             data-slot="accordion-trigger-icon"
             aria-hidden="true"
             viewBox="0 0 16 16"
             fill="none"
             {...stylex.props(styles.chevron)}
           >
             <path
               d="M4.75 6.75 8 10.25l3.25-3.5"
               stroke="currentColor"
               strokeWidth={1.5}
               strokeLinecap="round"
               strokeLinejoin="round"
               vectorEffect="non-scaling-stroke"
               {...stylex.props(styles.chevronPath)}
             />
           </svg>
         </AccordionPrimitive.Trigger>
       </AccordionPrimitive.Header>
     )
   }

   type AccordionContentProps = Omit<AccordionPrimitive.Panel.Props, "className" | "style"> &
     Overrides & { style?: CSSProperties }

   function AccordionContent({ xstyle, style, className, children, ...props }: AccordionContentProps) {
     const sx = stylex.props(styles.contentInner, xstyle)
     return (
       <AccordionPrimitive.Panel
         data-slot="accordion-content"
         {...props}
         {...stateStyles(
           (state) => [
             styles.content,
             (state.transitionStatus === "starting" || state.transitionStatus === "ending") &&
               styles.contentHidden,
           ],
           {
             style,
           },
         )}
       >
         <div data-slot="accordion-content-inner" {...sx} className={clsx(sx.className, className)}>
           {children}
         </div>
       </AccordionPrimitive.Panel>
     )
   }

   export { Accordion, AccordionContent, AccordionItem, AccordionTrigger }
   ```

4. Change the `@/` imports if your project uses different aliases.

## Usage

```tsx
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from "@/components/ui/accordion"
```

```tsx
<Accordion defaultValue={["item-1"]}>
  <AccordionItem value="item-1">
    <AccordionTrigger>Does it work with a keyboard?</AccordionTrigger>
    <AccordionContent>
      Yes. Tab moves between triggers, and Enter or Space opens one.
    </AccordionContent>
  </AccordionItem>
</Accordion>
```

`value` and `defaultValue` are arrays, one entry per open item, even when only
one item can be open at a time.

## Composition

```text
Accordion
├── AccordionItem
│   ├── AccordionTrigger
│   └── AccordionContent
└── AccordionItem
    ├── AccordionTrigger
    └── AccordionContent
```

`AccordionTrigger` renders the Base UI `Header` and `Trigger` together, and
`AccordionContent` renders the `Panel` around an inner element that holds the
padding.

## Multiple

Use the `multiple` prop to keep more than one item open at a time.

```tsx
import * as stylex from "@stylexjs/stylex"
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from "@/components/ui/accordion"
import { width } from "@/theme/tokens.stylex"

const styles = stylex.create({
  accordion: { maxWidth: width.lg },
})

const items = [
  {
    value: "reminders",
    trigger: "Reminders",
    content:
      "Choose when you hear about reviews that are due. Reminders arrive as a daily email digest or as a notification on your phone.",
  },
  {
    value: "access",
    trigger: "Sharing and access",
    content:
      "Decide who can open the workspace. Invite collaborators by email, require two-step sign-in and sign out devices you no longer use.",
  },
  {
    value: "plan",
    trigger: "Plan and invoices",
    content:
      "See which plan the workspace is on and download past invoices. Change the card on file or cancel the plan at any time.",
  },
]

export default function AccordionMultiple() {
  return (
    <Accordion multiple defaultValue={["reminders", "access"]} xstyle={styles.accordion}>
      {items.map((item) => (
        <AccordionItem key={item.value} value={item.value}>
          <AccordionTrigger>{item.trigger}</AccordionTrigger>
          <AccordionContent>{item.content}</AccordionContent>
        </AccordionItem>
      ))}
    </Accordion>
  )
}
```

## Disabled

Use the `disabled` prop on `AccordionItem` to disable a single item, or on
`Accordion` to disable all of them.

```tsx
import * as stylex from "@stylexjs/stylex"
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from "@/components/ui/accordion"
import { width } from "@/theme/tokens.stylex"

const styles = stylex.create({
  accordion: { maxWidth: width.lg },
})

export default function AccordionDisabled() {
  return (
    <Accordion xstyle={styles.accordion}>
      <AccordionItem value="members">
        <AccordionTrigger>How many people can join a workspace?</AccordionTrigger>
        <AccordionContent>
          Up to 50 on the standard plan. Owners add and remove members from the Members page in the
          workspace settings.
        </AccordionContent>
      </AccordionItem>
      <AccordionItem value="archive" disabled>
        <AccordionTrigger>Archived notebooks</AccordionTrigger>
        <AccordionContent>
          Archived notebooks are read-only. Restore the workspace to open this section.
        </AccordionContent>
      </AccordionItem>
      <AccordionItem value="email">
        <AccordionTrigger>How do I change my sign-in email?</AccordionTrigger>
        <AccordionContent>
          Change it under Account. We send a code to the new address, and the change applies once
          you enter it.
        </AccordionContent>
      </AccordionItem>
    </Accordion>
  )
}
```

## Borders

Items draw a rule along their bottom edge, except the last. Add a frame through
`xstyle` on the `Accordion` and inline padding on each `AccordionItem`.

```tsx
import * as stylex from "@stylexjs/stylex"
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from "@/components/ui/accordion"
import { radius, space, width } from "@/theme/tokens.stylex"

const styles = stylex.create({
  accordion: {
    maxWidth: width.lg,
    borderWidth: 1,
    borderStyle: "solid",
    borderRadius: radius.xl,
  },
  item: { paddingInline: space.s4 },
})

const items = [
  {
    value: "exports",
    trigger: "Which formats can I export?",
    content:
      "Markdown, PDF and LaTeX. Exports keep equations, figures and citations, and a notebook with data can include its CSV files.",
  },
  {
    value: "versions",
    trigger: "Can I restore an earlier version?",
    content:
      "Yes. Every save is kept in the notebook's history. Open a version to compare it with the current one, then restore it.",
  },
  {
    value: "citations",
    trigger: "How do citations work?",
    content:
      "Paste a DOI or an arXiv ID and the reference fills itself in. The bibliography at the end of the notebook updates as you cite.",
  },
]

export default function AccordionBorders() {
  return (
    <Accordion defaultValue={["exports"]} xstyle={styles.accordion}>
      {items.map((item) => (
        <AccordionItem key={item.value} value={item.value} xstyle={styles.item}>
          <AccordionTrigger>{item.trigger}</AccordionTrigger>
          <AccordionContent>{item.content}</AccordionContent>
        </AccordionItem>
      ))}
    </Accordion>
  )
}
```

## API reference

Pass `render` to replace a part's element or compose it with another component.

Every part wraps the Base UI `Accordion` part of the same name and accepts its
props. See the [Base UI reference](https://base-ui.com/react/components/accordion)
for the full list. Each part also takes `xstyle` and `className`.

### Accordion

| Prop               | Type                                 | Default |
| ------------------ | ------------------------------------ | ------- |
| `value`            | `string[]`                           | —       |
| `defaultValue`     | `string[]`                           | —       |
| `onValueChange`    | `(value: string[], details) => void` | —       |
| `multiple`         | `boolean`                            | `false` |
| `disabled`         | `boolean`                            | `false` |
| `keepMounted`      | `boolean`                            | `false` |
| `hiddenUntilFound` | `boolean`                            | `false` |

`hiddenUntilFound` hides a closed panel with `hidden="until-found"` instead of
unmounting it, which lets the browser's find-in-page reach the text and open
the item. It overrides `keepMounted`.

### AccordionItem

| Prop           | Type                               | Default |
| -------------- | ---------------------------------- | ------- |
| `value`        | `string`                           | —       |
| `disabled`     | `boolean`                          | —       |
| `onOpenChange` | `(open: boolean, details) => void` | —       |

An item with no `value` gets a generated one. Set it when you control the
accordion or want an item open on first render.

### AccordionTrigger

| Prop          | Type                     | Default |
| ------------- | ------------------------ | ------- |
| `headerProps` | `Accordion.Header.Props` | —       |
| `style`       | `CSSProperties`          | —       |

The heading is the primitive's `<h3>`. Pass
`headerProps={{ render: <h2 /> }}` to fit the page's outline.

`style` is real inline CSS, merged over the compiled styles.

### AccordionContent

`xstyle` and `className` apply to the inner element. `style` takes real inline
CSS on the panel. The panel animates its height between `0` and the measured
content height, and a padded box of height `0` still draws its padding.

### Data attributes

| Attribute                                  | On          | Effect                                       |
| ------------------------------------------ | ----------- | -------------------------------------------- |
| `data-slot="accordion-content"`            | the panel   | Targets the animated panel                   |
| `data-starting-style`, `data-ending-style` | the panel   | Base UI writes them while the panel animates |
| `data-open`, `data-disabled`               | item, panel | Base UI writes them                          |
| `data-panel-open`, `data-disabled`         | the trigger | Base UI writes them; the chevron flips       |
| `data-slot="accordion-trigger-icon"`       | the chevron | Targets the chevron from a parent            |

### CSS variables

| Variable                   | On        | Effect                                                          |
| -------------------------- | --------- | --------------------------------------------------------------- |
| `--accordion-panel-height` | the panel | Base UI writes the measured height; the panel transitions to it |
