Created
January 2, 2020 19:05
-
-
Save mminer/6a5395c32b4ba937b5233f47fefa0f57 to your computer and use it in GitHub Desktop.
React component for expanding and collapsing container with dynamic height.
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 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