Created
January 2, 2020 19:05
Star
You must be signed in to star a gist
React component for expanding and collapsing container with dynamic height.
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
import React, {forwardRef, useImperativeHandle, useRef} from 'react'; | |
interface Props { | |
children: React.ReactNode; | |
className?: string; | |
collapsedHeight: number; | |
isCollapsed: boolean; | |
transitionDuration?: string; | |
} | |
export interface VerticleCollapseRef { | |
getExpandedHeight: () => number; | |
} | |
function VerticalCollapse( | |
{children, className, collapsedHeight, isCollapsed, transitionDuration = '0.6s'}: Props, | |
ref: React.Ref<VerticleCollapseRef> | |
) { | |
const containerRef = useRef<HTMLDivElement>(null); | |
const getExpandedHeight = () => containerRef.current?.scrollHeight ?? collapsedHeight; | |
useImperativeHandle(ref, () => ({getExpandedHeight})); | |
return ( | |
<div | |
className={className} | |
ref={containerRef} | |
style={{ | |
maxHeight: isCollapsed ? collapsedHeight : getExpandedHeight(), | |
overflowY: 'hidden', | |
transitionProperty: 'max-height', | |
transitionDuration | |
}} | |
> | |
{children} | |
</div> | |
); | |
} | |
export default forwardRef(VerticalCollapse); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment