I am developing a collapsible list that only shows the first five items and a load more button at first, and when I click the load more button, the full list should be shown. I am using scrollHeight to determine this collapsible list's height and it works fine to show the first five items and the load more button, but after I click the load more button, the height of this collapsible list does not change and the remaining items cannot be displayed due to the height constraint. Does anyone have an idea how to fix it? Thank you so much, I really got stuck here for this whole day.
This is how this collapsible list looks like the collapsible list
This is the code of collapsible list
const Collapsible = ({ showCard, loaded, children }) => {
const collapsibleEl = useRef();
const [scrollHeight, setscrollHeight] = useState();
useEffect(() => {
setscrollHeight(collapsibleEl.current.scrollHeight);
console.log(collapsibleEl.current.scrollHeight);
}, [loaded, showCard]);
return (
<>
<div
className={styles.collapsible}
ref={collapsibleEl}
style={
showCard
? scrollHeight
? { height: `${scrollHeight + 100}px` }
: { height: `${collapsibleEl.current.scrollHeight + 100}px` }
: { height: "0px" }
}
>
{children}
</div>
</>
);
};
export default Collapsible;
I have figured it out, all I need to do is to use settimeout.
like this, just give it a little time to get the scrollheight and then re render.
useEffect(() => {
setTimeout(() => {
setscrollHeight(collapsibleEl.current.scrollHeight);
}, 300);
console.log(collapsibleEl.current.scrollHeight);
}, [showCard, loaded]);