ScrolltoIndex not working react-native on a flatlist

Joji Thomas picture Joji Thomas · Jul 25, 2018 · Viewed 17.4k times · Source

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>

Answer

Kirankumar Dafda picture Kirankumar Dafda · Jul 25, 2018

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});
};