lbry-desktop/ui/component/expandable/view.jsx

66 lines
1.7 KiB
React
Raw Normal View History

2018-11-07 23:44:38 +01:00
// @flow
import React, { useRef, useState } from 'react';
2018-11-07 23:44:38 +01:00
import classnames from 'classnames';
import Button from 'component/button';
2022-01-29 23:35:47 +01:00
import { useOnResize } from 'effects/use-on-resize';
2018-11-07 23:44:38 +01:00
2019-07-29 16:49:43 +02:00
const COLLAPSED_HEIGHT = 120;
2018-11-07 23:44:38 +01:00
type Props = {
2019-04-24 16:02:08 +02:00
children: React$Node | Array<React$Node>,
2018-11-07 23:44:38 +01:00
};
export default function Expandable(props: Props) {
const [expanded, setExpanded] = useState(false);
2022-01-29 23:35:47 +01:00
const [rect, setRect] = useState();
const { children } = props;
const ref = useRef();
2022-01-29 23:35:47 +01:00
// Update the rect initially & when the window size changes.
useOnResize(() => {
if (ref.current) {
setRect(ref.current.getBoundingClientRect());
}
});
// Update the rect when children changes,
// not sure if this is needed but a situation could arise when the
// component re-renders with a different children prop,
// Can enable on a later date if needed.
// useLayoutEffect(() => {
// console.log('render, useLayoutEffect');
// if (ref.current) {
// setRect(ref.current.getBoundingClientRect());
// }
// }, [children]);
2018-11-07 23:44:38 +01:00
function handleClick() {
setExpanded(!expanded);
2018-11-07 23:44:38 +01:00
}
return (
<div ref={ref}>
2019-07-29 16:49:43 +02:00
{rect && rect.height > COLLAPSED_HEIGHT ? (
2019-11-22 22:13:00 +01:00
<div ref={ref}>
<div
className={classnames({
'expandable--open': expanded,
'expandable--closed': !expanded,
})}
>
{children}
</div>
<Button
button="link"
className="expandable__button"
label={expanded ? __('Less') : __('More')}
onClick={handleClick}
/>
2018-11-07 23:44:38 +01:00
</div>
) : (
<div>{children}</div>
)}
</div>
);
2018-11-07 23:44:38 +01:00
}