Sometimes, we want to keep a ScrollView scrolled to the bottom with React Native.
In this article, we’ll look at how to keep a ScrollView scrolled to the bottom with React Native.
How to keep a ScrollView scrolled to the bottom with React Native?
To keep a ScrollView scrolled to the bottom with React Native, we can assign a ref to the ScrollView
and call scrollToEnd
on it.
For instance, we write:
import * as React from 'react';
import { View, Text, ScrollView, Button } from 'react-native';
import { Card } from 'react-native-paper';
const a = Array(50)
.fill()
.map((_, i) => i);
const App = () => {
const scrollViewRef = React.useRef();
const [arr, setArr] = React.useState(a);
return (
<View style={{ flex: 1 }}>
<Button onPress={() => setArr([...arr, ...a])} title="add" />
<ScrollView
style={{ height: '200px' }}
ref={scrollViewRef}
onContentSizeChange={() =>
scrollViewRef.current.scrollToEnd({ animated: true })
}>
{arr.map((i) => (
<Text>{i}</Text>
))}
</ScrollView>
</View>
);
};
export default App;
to assign a ref to the ScrollView
.
Then we set onContentSizeChange
to a function that calls scrollViewRef.current.scrollToEnd
with { animated: true }
to scroll to the bottom when the scroll height of the ScrollView
changes.
We add the ScrollView
content in between the ScrollView
tags.
And we add a Button
to add some content to the arr
array which is rendered in the ScrollView
.
Conclusion
To keep a ScrollView scrolled to the bottom with React Native, we can assign a ref to the ScrollView
and call scrollToEnd
on it.