initialScrollIndex not working for FlatList react native

sirilicious picture sirilicious · Jun 14, 2017 · Viewed 7.4k times · Source

I am experiencing an issue with the initialScrollIndex of FlatList - the argument of initialScrollIndex is simply ignored and the first item is shown.

https://snack.expo.io/Bk1mkK0zZ

Answer

Spliid picture Spliid · Jun 14, 2017

I had the exact same problem, which is why I found your question. After a lot of testing, I found a workaround, which seems to work. Instead of using initialScrollIndex I used the function scrollToIndex once the list is rendered. Applying it to your code, it will look like

import React, { Component } from 'react';
import { FlatList, Dimensions, View, Text } from 'react-native';

const WIDTH = Dimensions.get('window').width;
const HEIGHT = Dimensions.get('window').height;

export default class App extends Component {

  render() {
    const data = [{id: 0},{id: 1},{id: 2},{id: 3},{id: 4}];

     return (
      <View onLayout={() => this.onLayout()}>
        <FlatList
          ref={el => this.list = el}
          data={data}
          renderItem={this.renderItem}
          keyExtractor={item => item.id}

          pagingEnabled={true}
          horizontal={true}
          showsHorizontalScrollIndicator={false}

          getItemLayout={this.getItemLayout}

          debug={true}
        />
      </View>
    )
  }

  onLayout() {
    this.list.scrollToIndex({index: 2})
  }

  renderItem = ({ item }) => {
    return (
      <View style={{flex: 1, backgroundColor: 'lightblue', width: WIDTH, height: HEIGHT, justifyContent: 'center', alignItems: 'center'}}>
        <Text style={{color: 'white', fontSize: 300, fontWeight: 'bold'}}>{item.id}</Text>
      </View>
    );
  };

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

Hope it works for you.

By the way, putting this.list.scrollToIndex({index: 2}) in componentDidMount, does for some reason not work for me, which is why I used onLayout instead