Skip to content
Sancho UI
Toggle dark mode
Getting started
Built with ☕ by
Ben McMahen

Collapse

Collapse is used to hide and reveal content and works seamlessly with content of dynamic height.

You can build collapsing content using two exports:

  • Collapse: The main component which measures and reveals content.
  • useCollapse: A hook which helps control Collapse and provides the necessary aria-attributes.

Basic usage

If you control collapse using your own state, you are responsible for providing the necessary aria attributes.

const [show, setShow] = useState(false)

<Button
  onPress={() => setShow(true)}
  aria-expanded={show}
  aria-controls='collapse'>
    Expand
</Button>
<Collapse id='collapse' show={show}>
  Collapsed content
</Collapse>

Here's a more advanced example:

A funny dog

Roger

I'm your best friend.
I love food.
And I love walks.

Learn more
<Component initialState={{ show: false }}>
  {({ state, setState }) => {
    return (
      <Layer className="Collapse__example">
        <Embed width={707} height={448}>
          <img
            src={
              "https://images.unsplash.com/photo-1508280756091-9bdd7ef1f463?ixlib=rb-1.2.1&auto=format&fit=crop&w=1990&q=80"
            }
            alt="A funny dog"
          />
        </Embed>
        <div className="Collapse__content">
          <Text variant="h4">Roger</Text>
          <Collapse id="collapse" show={state.show}>
            <Text className="Collapse__text" variant="paragraph">
              I'm your best friend. <br />
              I love food. <br />
              And I love walks.
            </Text>
          </Collapse>
          <Button
            aria-controls="collapse"
            variant="ghost"
            intent="primary"
            iconAfter={state.show ? <IconChevronUp /> : <IconChevronDown />}
            onPress={() => setState({ show: !state.show })}
          >
            {state.show ? "Learn less" : "Learn more"}
          </Button>
        </div>
      </Layer>
    );
  }}
</Component>

Using hooks

The recommended way to control Collapse is by using the useCollapse hook, and binding the return value to the appropriate elements. This provides the recommended aria attributes.

import { Collapse, useCollapse } from 'sancho'

const Example = () => {
  const state = useCollapse(false)
  return (
    <div>
      <Button {...state.buttonProps}>
        Click to {state.show ? 'hide' : 'reveal'}!
      </Button>
      <Collapse {...state.collapseProps}>
        Collapse content
      </Collapse>
    </div>
  )
}

API

useCollapse
valueOf*() => boolean =
Returns the primitive value of the specified object.
Collapse
id*string
A unique id required for accessibility purposes.
show*boolean
Controls whether the children should be visible
children*ReactNode
Any element that you want to reveal