Search code examples
listreact-nativescrollreact-native-flatlist

ScrolltoIndex not working react-native on a flatlist


I'm using a flatList to render items from a json file, I want to scroll to a specific index when a button is pressed, I declared the function for button press as below

goIndex = () => {
    this.flatListRef.scrollToIndex({animated: true,index:5});
};

although it doesn't show any errors, the list is not moving to specified index.

react-native: 0.55.4

Attaching code of FlatList.

<View>
    <FlatList   
        getItemLayout={(data, index) => { return {length: 33, index, offset: 33 * index} }}
        ItemSeparatorComponent={ () => <View style={ { width:"100%", height: .7, backgroundColor: 'rgba( 52,52,52,1)' } } /> }
        data={this.state.outverse}
        renderItem={({item,index}) =>
            <View style={styles2.flatview}>
                <Text style={styles2.name}>{++index}  {item} </Text>
            </View>
        }
    />
</View>

Solution

  • Try adding reference to your FlatList component like below :

    <View>
        <FlatList   
            getItemLayout={(data, index) => { return {length: 33, index, offset: 33 * index} }}
            ItemSeparatorComponent={ () => <View style={ { width:"100%", height: .7, backgroundColor: 'rgba( 52,52,52,1)' } } /> }
            data={this.state.outverse}
            ref={(ref) => { this.flatListRef = ref; }}
            renderItem={({item,index}) =>
                <View style={styles2.flatview}>
                    <Text style={styles2.name}>{++index}  {item} </Text>
                </View>
            }
        />
    </View>
    

    And in goIndex function:

    goIndex = () => {
        this.refs.flatListRef.scrollToIndex({animated: true,index:5});
    };