Last active
March 25, 2022 06:13
-
-
Save AbdelrhmanAmin/142969e6cac80bff4068ea5e027590a9 to your computer and use it in GitHub Desktop.
JavaScript dynamic max height transition
This file contains 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
const INITIAL_MAX_HEIGHT = 10000; | |
const Collapse = ({ children }) => { | |
const collapseMenuRef = React.useRef(null); | |
const isFirstRender = React.useRef(true); | |
const maxHeightRef = React.useRef(INITIAL_MAX_HEIGHT); | |
const [isOpen, setOpen] = React.useReducer((state) => !state, false); | |
React.useEffect(() => { | |
if (collapseMenuRef.current && !isFirstRender.current) { | |
if ( | |
maxHeightRef.current > collapseMenuRef.current.offsetHeight && | |
maxHeightRef.current !== INITIAL_MAX_HEIGHT | |
) { | |
// HALT!! // Someone collapsed the menu too early! // The offsetHeight is not full. | |
return; | |
} | |
maxHeightRef.current = collapseMenuRef.current.offsetHeight; | |
} | |
if (isOpen && isFirstRender.current) { | |
isFirstRender.current = false; | |
} | |
}, [isOpen]); | |
return ( | |
<div | |
style={ | |
isOpen ? { maxHeight: maxHeightRef.current } : { maxHeight: 0 } | |
} | |
ref={collapseMenuRef} | |
> | |
{children} | |
</div> | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment