Collapsible

A UI component that allows content to be expanded or collapsed with a smooth animation.

Usage

<script>
  import { 
    Collapsible, 
    CollapsibleContent, 
    CollapsibleTrigger 
  } from "$lib/components/ui/collapsible";
</script>

<Collapsible>
  <CollapsibleTrigger>Toggle content</CollapsibleTrigger>
  <CollapsibleContent>
    <div class="p-4">
      Content that can be collapsed
    </div>
  </CollapsibleContent>
</Collapsible>

Examples

Basic Collapsible

A simple example with a button trigger

What are spells in magic.mov?

FAQ Style

A collapsible component styled as an FAQ item

API Reference

Collapsible

The main container component for the collapsible functionality.

PropTypeDefaultDescription
openboolean-Whether the content is expanded
onOpenChange(open: boolean) => void-Function called when open state changes
disabledbooleanfalseWhether the collapsible is disabled

CollapsibleTrigger

The trigger element that toggles the collapsible content.

PropTypeDefaultDescription
asChildbooleanfalseWhether to extend the component as a child

CollapsibleContent

The content area that expands or collapses.

PropTypeDefaultDescription
forceMountbooleanfalseForce the content to always be mounted

Implementation

The Collapsible component is built on top of the Bits UI library, which provides accessible primitives:

<!-- index.ts -->
import { Collapsible as CollapsiblePrimitive } from "bits-ui";

export const Root = CollapsiblePrimitive.Root;
export const Trigger = CollapsiblePrimitive.Trigger;
export const Content = CollapsiblePrimitive.Content;

export {
  Root as Collapsible,
  Trigger as CollapsibleTrigger,
  Content as CollapsibleContent
};

This implementation:

  • Uses accessible primitives that handle keyboard navigation and ARIA attributes
  • Manages the animation state automatically
  • Provides a clean API for creating collapsible components

Usage Notes

  1. The asChild prop on CollapsibleTrigger allows you to use your own component (like a Button) as the trigger.
  2. You can use the ui-open and ui-closed selectors for styling based on the collapsible state.
  3. For custom animations, target the CollapsibleContent with CSS transitions.
.collapsible-content {
  transition: height 0.2s ease;
}