I dynamically adding/removing elements and when the added element is not in the view port, I want to get that in to the view port by scrolling in to the added element.
However I can't get it working. I am using measure function to get the coordinates and then scrollTo function to scroll to the element.
Here is the parent component with scroll view
const scrollTo = (config) => {
scrollElRef.current.scrollTo(config);
};
return (
<ScrollView style={styles.container} ref={scrollElRef}>
<Text style={styles.paragraph}>
aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto
beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia
voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni
dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam
est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit.
</Text>
<Card>
{items.map((i) => <AssetExample key={i} scrollTo={(c) => scrollTo(c)}/>)}
</Card>
</ScrollView>
);
}
Here is the child component which add/remove element and sends the coordinates to the parent view
React.useEffect(() => {
if(asset) {
elRef.current.measure((x, y, w, h, pageX, pageY) => {
const elementBottom = pageY + h;
const isInViewport = elementBottom < height;
if (!isInViewport) {
scrollTo({y: pageY, animated: true});
}
});
}
}, [asset, scrollTo, height])
Here is a sample App, which shows the problem.