React Native: easily scroll to a specific element in a list on the page

If you need to scroll to a specific View on a page, specified by a prop scrollToId to that page, do something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
render() {
const { entities, scrollToId } = this.props;

return (
<ScrollView ref={ref => {this.scrollerRef = ref; }}>
{entities.map((entity) => {
const scrollThis = scrollToId != null && scrollToId === entity.id;

return (
<View
key={entity.id}
ref={scrollThis ? (ref) => { this.scrollToRef = ref; } : undefined}
onLayout={scrollThis ? this.onLayout : undefined}
>
<Text>Some stuff to show from entity</Text>
</View>
);
})}
</ScrollView>
);
}

onLayout = () => {
this.scrollToRef.measure((x, y, width, height, pageX, pageY) => {
if (this.scrollerRef) this.scrollerRef.scrollTo({ x: pageX, y: pageY });
});
}

entities is assumed to be a list of something you want to render, with a unique prop id.