FAQ accordion

An accessible accordion for questions and answers: each question is a heading with a button (aria-expanded, aria-controls) that opens a labelled region, closed answers are inert, arrow keys, Home and End move between questions, and answers open with a smooth height animation that turns off under reduced motion. Single or multiple open, collapsible, default open items and a configurable heading level.

MarketingComponentTailwind v4

Source

"use client";

import { useId, useRef, useState, type KeyboardEvent, type ReactNode } from "react";
import { Plus } from "lucide-react";
import { cn } from "@/lib/utils";

export type FaqItem = {
  /** Stable id, used for defaultOpen and the DOM ids. Defaults to the item's position. */
  id?: string;
  question: string;
  answer: ReactNode;
};

export type FaqAccordionProps = {
  items: FaqItem[];
  /** "single" keeps one answer open at a time; "multiple" lets any number stay open. */
  type?: "single" | "multiple";
  /** Ids (or positions as strings) open on first render. */
  defaultOpen?: string[];
  /** In single mode, allow closing the open item so none is open. */
  collapsible?: boolean;
  /** Heading level that wraps each question, to fit the page outline. */
  headingLevel?: 2 | 3 | 4 | 5 | 6;
  onOpenChange?: (open: string[]) => void;
  className?: string;
};

export function FaqAccordion({
  items,
  type = "single",
  defaultOpen = [],
  collapsible = true,
  headingLevel = 3,
  onOpenChange,
  className,
}: FaqAccordionProps) {
  const baseId = useId();
  const [open, setOpen] = useState<string[]>(type === "single" ? defaultOpen.slice(0, 1) : defaultOpen);
  const triggers = useRef<(HTMLButtonElement | null)[]>([]);
  const Heading = `h${headingLevel}` as "h3";

  const toggle = (key: string) => {
    const isOpen = open.includes(key);
    let next: string[];
    if (type === "single") next = isOpen ? (collapsible ? [] : open) : [key];
    else next = isOpen ? open.filter((value) => value !== key) : [...open, key];
    setOpen(next);
    onOpenChange?.(next);
  };

  // Arrow keys, Home and End move between questions, as the WAI-ARIA accordion pattern suggests.
  const onKeyDown = (event: KeyboardEvent<HTMLButtonElement>, index: number) => {
    const last = items.length - 1;
    const target = { ArrowDown: index === last ? 0 : index + 1, ArrowUp: index === 0 ? last : index - 1, Home: 0, End: last }[event.key];
    if (target === undefined) return;
    event.preventDefault();
    triggers.current[target]?.focus();
  };

  return (
    <div className={cn("flex flex-col gap-2", className)}>
      {items.map((item, index) => {
        const key = item.id ?? String(index);
        const isOpen = open.includes(key);
        const triggerId = `${baseId}-trigger-${index}`;
        const panelId = `${baseId}-panel-${index}`;
        return (
          <div
            key={key}
            data-state={isOpen ? "open" : "closed"}
            className={cn("rounded-lg transition-colors duration-200", isOpen ? "bg-muted" : "bg-muted/50 hover:bg-muted/80")}
          >
            <Heading className="m-0">
              <button
                ref={(node) => { triggers.current[index] = node; }}
                id={triggerId}
                type="button"
                aria-expanded={isOpen}
                aria-controls={panelId}
                onClick={() => toggle(key)}
                onKeyDown={(event) => onKeyDown(event, index)}
                className="flex w-full items-center justify-between gap-6 rounded-lg px-5 py-4 text-left text-base font-medium text-foreground outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background sm:px-6 sm:py-5"
              >
                <span>{item.question}</span>
                <Plus
                  aria-hidden="true"
                  className={cn("size-5 shrink-0 text-muted-foreground motion-safe:transition-transform motion-safe:duration-300", isOpen && "rotate-45 text-foreground")}
                />
              </button>
            </Heading>
            <div
              id={panelId}
              role="region"
              aria-labelledby={triggerId}
              inert={!isOpen || undefined}
              className={cn(
                "grid motion-safe:transition-[grid-template-rows,opacity] motion-safe:duration-300 motion-safe:ease-out",
                isOpen ? "grid-rows-[1fr] opacity-100" : "grid-rows-[0fr] opacity-0",
              )}
            >
              <div className="overflow-hidden">
                <div className="max-w-prose px-5 pb-5 text-[0.9375rem] leading-relaxed text-muted-foreground sm:px-6 sm:pb-6">{item.answer}</div>
              </div>
            </div>
          </div>
        );
      })}
    </div>
  );
}