InitialScrollIndex not working for FlatList

I had a problem with initialScrollIndex from FlatList - the initialScrollIndex argument is simply ignored and the first element is displayed.

https://snack.expo.io/Bk1mkK0zZ

+4
source share
3 answers

I had the same problem, so I found your question. After a lot of testing, I found a workaround that seems to work. Instead of using it, initialScrollIndexI used the function scrollToIndexafter displaying the list. 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 this works for you.

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

+1

, . WIDTH 0 , onLayout . , initialScrollIndex, . Dimensions, , .

0

Here is my workaround (for horizontal, you can adjust for vertical):

<FlatList
  horizontal
  contentOffset = {{x: ITEM_WIDTH * this.props.startAtIndex, y: 0}}
  ...
/>
0
source

Source: https://habr.com/ru/post/1679232/


All Articles