Sometimes, we want to scroll to top of the ScrollView with React Native.
In this article, we’ll look at how to scroll to top of the ScrollView with React Native.
How to scroll to top of the ScrollView with React Native?
To scroll to top of the ScrollView with React Native, we assign a ref to the ScrollView
and call scrollTo
on the ref’s value.
For instance, we write:
import * as React from 'react';
import { ScrollView, View, Text, Button } from 'react-native';
import Constants from 'expo-constants';
import { Card } from 'react-native-paper';
export default function App() {
const ref = React.useRef();
return (
<View
style={{
flexGrow: 1,
}}>
<Button
title="scroll to top"
onPress={() => {
ref.current.scrollTo(0);
}}
/>
<ScrollView ref={ref} style={{ height: 200 }}>
{Array(200)
.fill()
.map((_, i) => {
return <Text>{i}</Text>;
})}
</ScrollView>
</View>
);
}
to create a ref with useRef
and set that as the value of the ref
prop of the ScrollView
.
Then we add a Button
that calls ref.current.scrollTo
with 0 to scroll the ScrollView
to the top when it’s pressed.
Conclusion
To scroll to top of the ScrollView with React Native, we assign a ref to the ScrollView
and call scrollTo
on the ref’s value.