Introducing PrimeReact v11-alpha 🎉Discover Now

useCollapsible

Hook that manages open/close state, toggle behavior, and ARIA attributes for collapsible content.

basic-demo

Usage#

import { useCollapsible } from '@primereact/headless/collapsible';
 
const { rootProps, triggerProps, contentProps, state } = useCollapsible();
 
return (
    <div {...rootProps}>
        <button {...triggerProps}></button>
        {state.open && <div {...contentProps}></div>}
    </div>
);

useCollapsible manages open/close state with toggle, open, and close methods — see Primitive for a component-based API.

Features#

  • Returns spread-ready rootProps, triggerProps, and contentProps with ARIA and data attributes
  • Supports controlled (open) and uncontrolled (defaultOpen) modes
  • Provides toggle, open, and close methods for imperative control
  • Fires onOpen, onClose, and onOpenChange callbacks

Behavior#

Default State#

The collapsible starts open by default. Set defaultOpen to false to start collapsed.

const { state } = useCollapsible({ defaultOpen: false });
 
state.open; // false

Controlled#

Pass open and onOpenChange to control the state externally.

const [isOpen, setIsOpen] = React.useState(true);
const { state } = useCollapsible({ open: isOpen, onOpenChange: (e) => setIsOpen(e.value) });

Disabled#

Set disabled to prevent toggling and remove the trigger from the tab order.

const { triggerProps } = useCollapsible({ disabled: true });
 
triggerProps.tabIndex; // -1
triggerProps['aria-disabled']; // true

Custom Styling with Data Attributes#

The prop objects include data-scope="collapsible" and data-part for styling. State is reflected via data-open/data-closed on root and content, and data-content-open/data-content-closed on trigger.

[data-scope='collapsible'][data-part='root'][data-open] {
    border-color: var(--p-primary-color);
}
 
[data-scope='collapsible'][data-part='trigger'][data-content-open] svg {
    transform: rotate(180deg);
}

API#

useCollapsible#

NameTypeDefault
openbooleanfalse
Controls the open state of the collapsible.
defaultOpenbooleanfalse
Defines the initial open state of the collapsible.
disabledbooleanfalse
When disabled, the component cannot be interacted with.
tabIndexnumber0
Index of the element in tabbing order.
onOpen(event?: SyntheticEvent) => void—
Callback triggered when the content is opened.
onClose(event?: SyntheticEvent) => void—
Callback triggered when the content is closed.
onOpenChange(event: useCollapsibleOpenChangeEvent) => void—
Callback triggered when the content's toggle state changes.

Accessibility#

See Collapsible Primitive for WAI-ARIA compliance details and keyboard support.