Shopify / flash-list

A better list for React Native
https://shopify.github.io/flash-list/
MIT License
5.39k stars 276 forks source link

scrollToOffset/index in horizontal direction with paging is wrong #613

Closed segicm closed 1 year ago

segicm commented 1 year ago

Current behavior

I am having a long list of items rendered in a Horizontal direction. On a button press, I want to scroll to a certain item in the list. The problem is that the "scrollToOffset" and "scrollToIndex" are not scrolling me to the middle of the item as it is shown on the screenshot. The first few items are centered but if I try to scroll to a 15. item, for example, then it gets it wrong.

Simulator Screen Shot - iPhone 12 Pro - 2022-09-25 at 11 12 36

My code:

<FlashList
    ref={flatListRef}
    data={data}
    renderItem={renderItem}
    horizontal
    pagingEnabled
    showsHorizontalScrollIndicator={false}
    estimatedItemSize={400}
    viewabilityConfigCallbackPairs={viewabilityConfigCallbackPairs.current}
  />

The render item wrapper has a width equal to the width of the device screen.

This is how I am trying to scroll to the item.

flatListRef?.current?.scrollToOffset({
    offset: width * index,
    animated: true,
  });

Expected behavior

This is how it looks when I scroll to the first five items, and this is how it should be for the all items on the list. Simulator Screen Shot - iPhone 12 Pro - 2022-09-25 at 11 12 45

To Reproduce

Platform:

Environment

1.1.0

naqvitalha commented 1 year ago

Can you create an expo snack for this? I can take a look

segicm commented 1 year ago

I have tried to recreate the problem, that I have, on the Expo Snack and everything worked fine. So, I started digging more into the problem on my side and discovered that my custom hook created this problem. I think the problem is that the hook is rerendering the item at the same time when the scrollToOffset is working.

Here is an example on the snack: https://snack.expo.dev/@sega93/upbeat-strawberries

(Run it on iOS or Android mode)

fkranenburg commented 1 year ago

I have the same issue but not using hook or anything. The issue is reproducable when you add onLoad={()=>scrollToOff(99)} on above slack of @segicm . It also happens when adding initialScrollIndex={99} for example.

segicm commented 1 year ago

@fkranenburg check your estimatedItemSize prop. It should have the correct measurements of the item's width/height. I have resolved the problem by updating it to estimatedItemSize={Dimensions.get("window").width}

fkranenburg commented 1 year ago

@segicm thanks! That was indeed the issue.

naqvitalha commented 1 year ago

Closing as this seems to be resolved with right estimates

laugepetersen commented 6 months ago

This seems to be off when the amount of columns in a horizontal scroll is odd. In my case a weekly calender of 7 items seems to be offset wierd due to the division resulting in possible a long float.