0

I'm working on something like instagram snap scrolling. The User Card should be centered (One card on each scroll).

  <FlatList
    data={items}
    renderItem={({item}) => <UserCardComponent name={item.name} />}
    keyExtractor={item => item.id}
    snapToAlignment="center"
    decelerationRate={'fast'}
    snapToInterval={Dimensions.get('window').height}
    showsVerticalScrollIndicator={false}
  />

This is working fine after scrolling from the second item onwards or when we touch it, it is adjusting to center but when it is rendered first time its not in the center.

User Card Component looks like this on first render

Second Item After scrolling

Second item is perfectly centered, I want first item to be centered.

I tried to move the card upwards using useEffect with these functions scrollToOffset,scrollToItem, scrollToIndex etc. but they needed flatlist reference which is not available while rendering first time.

Thanks in advance. Any help will be appreciated

Ken White
  • 123,280
  • 14
  • 225
  • 444
Akshay Kumar
  • 11
  • 1
  • 2

1 Answers1

2

You will need to use scrollToIndex method of FlatList and scroll to the desired index using onLayout event

In the scrollToIndex call, pass viewPosition value of 0.5 which will center the view (snap in your case)

https://reactnative.dev/docs/flatlist#scrolltoindex

const ref = useRef<FlatList>(null);

const onLayout = () => {
    ref.current?.scrollToIndex({
        index: 10,
        viewPosition: 0.5,
    });
};

<FlatList
    ref={ref}
    onLayout={onLayout}
    snapToAlignment={'center'}
    ...
/>