scrollToLocation always scrolling to top in sectionList in react native

617 Views Asked by At

I am using a simple function to scroll to index in section list in react native;

let sectionIndex = route.params.index;

sectionListRef?.current?.scrollToLocation({
        sectionIndex,
        itemIndex: 0,
});

where sectionIndex in coming from route params. Though I though that may be causing the problem, but i created a button to scroll to a particular index and even gave a number as the index instead of using the one coming from route params. But it doesn't work, it is just ignoring the sectionIndex and always scrolling to top (if not at the top).

There is no more relevant code but anyways, here is my sectionList:

<SectionList
        ref={sectionListRef}
        refreshing={isFetching}
        onRefresh={refetch}
        sections={boards ?? []}
        renderItem={renderItem}
        ListEmptyComponent={
          !isFetching ? <NoBoards screenname="board" /> : null
        }
        ListFooterComponent={<VStack padding="5" />}
        renderSectionHeader={Sectionheader}
        stickySectionHeadersEnabled
      />
2

There are 2 best solutions below

5
kiuQ On

I recreated the issue using your expo snack. I believe the issue is about the main container view. It is better to provide flex: 1 in the container style.

import { useRef } from 'react';
import { SectionList, View, Text, Button } from 'react-native';

const data = [
  { title: 'title 1', data: [1, 2, 3, 4] },
  { title: 'title 2', data: [1, 2, 3, 4] },
  { title: 'title 3', data: [1, 2, 3, 4] },
  { title: 'title 4', data: [1, 2, 3, 4] },
  { title: 'title 5', data: [1, 2, 3, 4] },
  { title: 'title 6', data: [1, 2, 3, 4] },
  { title: 'title 7', data: [1, 2, 3, 4] },
  { title: 'title 8', data: [1, 2, 3, 4] },
  { title: 'title 9', data: [1, 2, 3, 4] },
  { title: 'title 10', data: [1, 2, 3, 4] },
];

const App = () => {
  const sectionListRef = useRef(null);

  return (
    //Section List will always scroll to the top if this flex prop is removed
    <View style={{flex: 1}}>
      <View style={{flexDirection: 'row', marginTop: 50, justifyContent: 'space-around'}}>
        <Button 
          title={"Top"} 
          onPress={()=>{sectionListRef?.current?.scrollToLocation({sectionIndex: 0, itemIndex: 0})}}
        />
        <Button 
          title={"Bottom"} 
          onPress={()=>{sectionListRef?.current?.scrollToLocation({sectionIndex: 6, itemIndex: 0})}} 
        />
      </View>

      <SectionList
        ref={sectionListRef}
        renderSectionHeader={({section}) => <Text>{section.title}</Text>}
        stickySectionHeadersEnabled
        sections={data}
        renderItem={({ item }) => (
          <View style={{ padding: 20 }}>
            <Text>{item}</Text>
          </View>
        )}
      />
    </View>
  );
};

export default App;
2
valeshgopal On

Not sure why, but itemIndex: 1 has made it work