-
Notifications
You must be signed in to change notification settings - Fork 3.4k
/
ExpandingContainer.jsx
43 lines (40 loc) · 1.07 KB
/
ExpandingContainer.jsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import React, { useState, useEffect, useRef } from 'react';
import { bool } from 'prop-types';
import styled from 'styled-components';
const Container = styled.div`
margin: 15px 0;
transition: height 0.2s ease-out;
${props => props.hideOverflow && `overflow: hidden;`}
`;
function ExpandingContainer({ isExpanded, children }) {
const [contentHeight, setContentHeight] = useState(0);
const [hideOverflow, setHideOverflow] = useState(!isExpanded);
const ref = useRef(null);
useEffect(() => {
ref.current.addEventListener('transitionend', () => {
setHideOverflow(!isExpanded);
});
});
useEffect(() => {
setContentHeight(ref.current.scrollHeight);
}, [setContentHeight]);
const height = isExpanded ? contentHeight : '0';
return (
<Container
ref={ref}
css={`
height: ${height}px;
`}
hideOverflow={!isExpanded || hideOverflow}
>
{children}
</Container>
);
}
ExpandingContainer.propTypes = {
isExpanded: bool,
};
ExpandingContainer.defaultProps = {
isExpanded: false,
};
export default ExpandingContainer;