Skip to main content

Recipes

Because the trigger and panel elements can be rendered anywhere within a Collapsible component, you can easily create more complex behaviors and layouts by combining Collapsible with other components. Just remember that the base Collapsible component needs to be above both the panel and the trigger in the tree.

Live Editor
function CollapsibleRecipeExample1() {
  const [open, setOpen] = React.useState(false);
  const toggle = () => setOpen(!open);

  return (
    <Box display="flex">
      <Collapsible isOpen={open}>
        <Box width="75px" mr={400}>
          <Collapsible.Trigger>
            <Button appearance="secondary" onClick={toggle} width={1}>
              {open ? 'Hide' : 'Show'}
            </Button>
          </Collapsible.Trigger>
        </Box>

        <Box flex={1}>
          <Text as="p" fontWeight="semibold" mt={-300}>
            Click the button to the left if you'd like to learn more about the
            content on the right.
          </Text>

          <Collapsible.Panel>
            <Box
              mt={350}
              width="100%"
              height="200px"
              bg="app.background.base"
              display="flex"
              alignItems="center"
              justifyContent="center"
            >
              Hey there!
            </Box>
          </Collapsible.Panel>

          <Text as="p" fontSize={200} color="text.subtext" mt={300}>
            Here's some footer text.
          </Text>
        </Box>
      </Collapsible>
    </Box>
  );
}

Collapsible also has niche use cases where an element may need to visually display inner content while collapsed. This behavior can be achieved via the collapsedHeight and openHeight props, which basically act as min-height and max-height for open and closed states. Setting these values may trigger a scroll if your content overflows beyond the values you've selected.

Live Editor
function CollapsibleRecipeExample2() {
  const [open, setOpen] = React.useState(false);
  const toggle = () => setOpen(!open);

  return (
    <Box>
      <Collapsible isOpen={open} collapsedHeight={50} openHeight={100}>
        <Collapsible.Trigger>
          <Button appearance="secondary" onClick={toggle} width={1}>
            {open ? 'Hide' : 'Show'}
          </Button>
        </Collapsible.Trigger>

        <Collapsible.Panel>
          <Box mt={350} width="100%" height="200px" bg="app.background.base">
            <Text>Hey there!</Text>
            <Text mt={30}>A lot to see here if you scroll.</Text>
            <Text mt={30}>Oops! That's all there is.</Text>
          </Box>
        </Collapsible.Panel>
      </Collapsible>
    </Box>
  );
}