useCollapse

React hook that helps creating accesssible Collapse components.

useCollapse works similar to useDisclosure, but adds a few extra options specifically for the Collapse component.

getCollapseProps returns an in prop instead of hidden and setting isCollapsible to false will omit the aria tags and click handler for the toggle element.

Import#

import { useCollapse } from '@saas-ui/react'

Parameters#

NameTypeDescription
defaultIsOpenbooleanSet the collapse to open by default.
onOpen() => voidCallback function, called when the collapse opens.
onClose() => voidCallback function, called when the collapse closes.
isCollapsiblebooleanSet this to false to disable the collapse.

Return value#

The useCollapse hook returns the isOpen state and two prop getter functions.

NameTypeDescription
isOpenbooleanBoolean that indicates if the collapse is open or closed.
getToggleProps(props) => ObjectReturns properties for the toggle element.
getCollapseProps(props) => ObjectReturns properties for the collapse element.
onOpen() => voidOpen the collapse.
onClose() => voidClose the collapse.
onToggle() => voidToggle the collapse.

Accessibility#

Adds aria-expanded and aria-controls tags to the toggle component and a unique id collapse-[n] to the collapse.

Usage#

Basic usage#

function NavGroup({
defaultIsOpen = true,
title = 'Nav group',
children = (
<>
<Link>Home</Link>
</>
),
}) {
const { isOpen, getToggleProps, getCollapseProps } = useCollapse({
defaultIsOpen,
})
const headingStyles = {
cursor: 'pointer',
borderRadius: 'md',
userSelect: 'none',
p: 2,
_hover: {
bg: 'gray.600',
},
}
return (
<Box p="8">
<Heading sx={headingStyles} size="md" {...getToggleProps()}>
{title}
</Heading>
<Collapse {...getCollapseProps()}>
<Box p={2}>{children}</Box>
</Collapse>
</Box>
)
}

Props#

Was this helpful?