Skip to content

Instantly share code, notes, and snippets.

@mminer
Created January 2, 2020 19:05
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save mminer/6a5395c32b4ba937b5233f47fefa0f57 to your computer and use it in GitHub Desktop.
React component for expanding and collapsing container with dynamic height.
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