Skip to content

Instantly share code, notes, and snippets.

@zmajstor
Created November 10, 2024 18:54
Show Gist options
  • Save zmajstor/d2339913b4c79db752417ad417109375 to your computer and use it in GitHub Desktop.
Save zmajstor/d2339913b4c79db752417ad417109375 to your computer and use it in GitHub Desktop.
import { useCollapsible } from '../hooks/useCollapsible'
export const Component = ({}) => {
const {
isOpen: isCredentialsOpen,
toggle: toggleCredentials,
height: collapsableCredentialsHeight,
ref: collapsableCredentialsRef
} = useCollapsible()
return (
<>
<h4 onClick={toggleCredentials}>
<span style={{ width: '16px', display: 'inline-block' }}>
{isCredentialsOpen ? '▼' : '►'}
</span>
Credentials
</h4>
<div
ref={collapsableCredentialsRef}
style={{
height: collapsableCredentialsHeight,
overflow: 'hidden',
transition: 'height 0.3s ease-out'
}}
>
content
</div>
</>
)
}
import { useState, useEffect, useRef } from 'react'
export const useCollapsible = () => {
const [isOpen, setIsOpen] = useState(false)
const [height, setHeight] = useState(0)
const collapsableContentRef = useRef(null)
const toggle = () => {
setIsOpen((prev) => !prev)
}
useEffect(() => {
if (collapsableContentRef.current) {
setHeight(isOpen ? collapsableContentRef.current.scrollHeight : 0)
}
}, [isOpen])
return { isOpen, toggle, height, ref: collapsableContentRef }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment