In my react app I'm doing some kind of animations to make it nicer. I want to make a div appear by sliding from above disappear by sliding it back.
I'm using bootstrap 5.1.0
and react-bootstrap 1.6.1
in my stack.
I came up with a solution that is to wrap the content inside a div and toggle its maxHeight
between window.innerHeight
and 0
as needed. I added also a custom css class
.transition-height{
transition: max-height 0.5s ease-in-out;
}
Problem is that obviosly, when I close the div, the animation starts from a very hight value of maxHeight and so there's a delay between the close trigger event and the moment when you see the div actually closing. I used window.innerHeight
as I don't have a known height target value to use, it depends from the length of div content.
I uploaded the code to codesandbox, so you can see its behaviour.
How can I avoid this?
CodePudding user response:
In your case just need to get the height of the div with useRef and when will show = true set the current height. codesandbox exapmle
ApperDiv
const AppearDiv = (props) => {
let { show = false, className = "", style = {} } = props;
const ref = useRef(null);
const getPaperBoxHeight = ref.current?.scrollHeight || 0;
const filteredProps = Object.entries(props)
.filter(([k, _]) => !["className", "show", "style"].includes(k))
.reduce((p, [k, v]) => ({ ...p, [k]: v }), {});
style = show ? { height: getPaperBoxHeight } : { height: 0 };
return (
<div
ref={ref}
className={
"overflow-hidden transition-height" (className && ` ${className}`)
}
style={style}
{...filteredProps}
/>
);
};