Created
November 10, 2024 18:54
-
-
Save zmajstor/d2339913b4c79db752417ad417109375 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> | |
</> | |
) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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