SwipeableViews How to pass the updateHeight() as a prop

Viewed 268

So I am using SwipeableViews no swipe between pages. My problem is each page have a different dynamic length. I have animateHeight as true but it only animate the height when the tab changes. In the documentation it says that the function updateHeight() can solve this. https://react-swipeable-views.com/api/api/

Due to my lack of knowledge I just could not get the updateHeight since all the exampels I saw on class based app. I built my app in function based app. I just could not figure it out to pass it as props to call it later.

1 Answers

I've found a way to use the updateHeight function. It's a bit hacky, but it works . I've added an interval and timeout to compensate for data loading in/slow machines. The useEffect cleans the interval when the page is unmounted.

There's probably a better solution, but this is what I've found so far!

export function SwipeView() {
 const [ref, setRef] = useState(null);

 const onRefChange = useCallback((node: SwipeableViews & HTMLDivElement) => {
   // hacky solution to update the height after the first render. Height is not set correctly on initial render
 setRef(node); // e.g. change ref state to trigger re-render
   if (node === null) {
     return;
   } else {
     interval = setInterval(() => {
       // @ts-ignore typings are not correct in this package
       node.updateHeight();
     }, 100);
     setTimeout(() => {
       clearInterval(interval);
     }, 10000);
   }
 }, []);

 useEffect(() => {
   return () => clearInterval(interval);
 }, [interval]);

 return (
   <SwipeableViews
     animateHeight
     ref={onRefChange}
   >
     {children}          
   </SwipeableViews>
 );
}
Related