Saturday, June 3, 2017

Scroll to end of FlatList after displaying the keyboard

Leave a Comment

I have a FlatList inside a KeyboardAvoidingView. When the keyboard is displayed I would like to scroll to the end of the FlatList.

I am listening for the 'keyboardDidShow' event which does get fired, but it may be fired too early as the FlatList is not scrolled to the end after calling scrollToEnd.

I have looked into the onLayout event of KeyboardAvoidingView however just setting the onLayout event to trigger a function seems to stop the KeyboardAvoidingView from adjusting it's size when the Keyboard is shown.

<KeyboardAvoidingView behavior='padding' style={{ flex: 1}} onLayout={this._scrollEnd}> 

Code:

import React from 'react'; import {Image, Linking, Platform, ScrollView, StyleSheet, Text, TouchableOpacity, View, Button, Alert, FlatList, TextInput, KeyboardAvoidingView, Keyboard} from 'react-native'; import { MonoText } from '../components/StyledText';  export default class HomeScreen extends React.Component {   constructor() {     super();     this.state = {       messages: getMessages()     };      this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this._scrollEnd);     this.keyboardDidShowListener = Keyboard.addListener('keyboardDidHide', this._scrollEnd);   }    _scrollEnd = (evt) => {     this.refs.flatList1.scrollToEnd();   }    render() {     return (       <KeyboardAvoidingView behavior='padding' style={{ flex: 1}} >         <FlatList           style={{ flex:1}}           ref="flatList1"           data={this.state.messages}           renderItem={({ item }) => <Text>{item.text}</Text>}         />       </KeyboardAvoidingView>     );   } } 

1 Answers

Answers 1

As stated in above comment, getItemLayout should resolve your issue.

According to Reactive FlatList documentation:

getItemLayout is an optional optimizations that let us skip measurement of dynamic content if you know the height of items a priori. getItemLayout is the most efficient, and is easy to use if you have fixed height items, for example:

getItemLayout={(data, index) => (   {length: ITEM_HEIGHT, offset: ITEM_HEIGHT * index, index} )} 

If you use ItemSeparatorComponent, don't forget to incorporate the separator height or width when calculating the resulting offset.

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment