Sometimes, we want to scroll to end of FlatList after displaying the keyboard with React Native.
In this article, we’ll look at how to scroll to end of FlatList after displaying the keyboard with React Native.
How to scroll to end of FlatList after displaying the keyboard with React Native?
To scroll to end of FlatList after displaying the keyboard with React Native, we can set the onLayour
prop to a function that calls scrollToEnd
on the FlatList’s ref.
For instance, we write:
import * as React from 'react';
import { FlatList, Text, View } from 'react-native';
import Constants from 'expo-constants';
import { Card } from 'react-native-paper';
const flatListItems = Array(200)
.fill()
.map((_, i) => ({ title: i, id: i }));
const Item = ({ title }) => (
<View
style={{
backgroundColor: '#f9c2ff',
padding: 20,
marginVertical: 8,
marginHorizontal: 16,
}}>
<Text>{title}</Text>
</View>
);
export default function App() {
const renderItem = ({ item }) => <Item title={item.title} />;
const flatListRef = React.useRef();
return (
<View style={{ height: 300 }}>
<FlatList
ref={flatListRef}
data={flatListItems}
renderItem={renderItem}
keyExtractor={(item) => item.id}
onLayout={() => flatListRef.current.scrollToEnd({ animated: true })}
/>
</View>
);
}
to set onLayout
to a function that calls flatListRef.current.scrollToEnd
to scroll the FlatList to the end.
We create the ref with useRef
and assigned it as the value of the FlatList
‘s ref
prop.
Conclusion
To scroll to end of FlatList after displaying the keyboard with React Native, we can set the onLayour
prop to a function that calls scrollToEnd
on the FlatList’s ref.