Search code examples
reactjsreact-spring

Add default open logic for a react Collapse component


I created this react Collapse component with react-spring which have the open and close functionality.

I want to have a defaultOpen prop, so the content stays open on initial render then it use isOpen state for closing and opening.

How can i do that?

here is a codesandbox link: https://codesandbox.io/s/awesome-fire-wsvml


Solution

  • For that, you will need to have Collapsible component own state

    And pass defaultOpen from the parent component

    Something like this:

    const Collapse = ({ defaultOpen = false, children }) => {
      const [isOpen, setIsOpen] = useState(defaultOpen)
      const [ref, { height: viewHeight }] = useMeasure()
      const { height, opacity } = useSpring({
        from: { height: 0, opacity: 1 },
        to: {
          height: isOpen ? viewHeight : 0,
          opacity: isOpen ? 1 : 0,
        },
      })
    
      return (
        <>
          <button onClick={() => setIsOpen(isOpen => !isOpen)}>{isOpen ? 'close' : 'open'}</button>
          <Content style={{ opacity, height }}>
            <a.div ref={ref}>{children}</a.div>
          </Content>
        </>
      )
    }
    

    Working Example:

    Edit eloquent-mccarthy-ce2w7