After calling scrollToLocation method of SectionList, scroll is jumping

Viewed 1768

I want to implement something like scrollspy on the web with section list. I'm using scrollToLocation method. The problem is when scrolling is finished the scroll is jumping. I think it causes by loading previous rows. I don't know why this issue happens even when providing getItemLayout prop. Here is a basic demo. You can find the complete code example here.

enter image description here

This is my section list:

 <SectionList
    style={{ backgroundColor: 'blue' }}
    renderItem={this.renderItem}
    renderSectionHeader={this.renderSectionHeader}
    sections={sections}
    keyExtractor={(item, index) => item.id}
    getItemLayout={this.getItemLayout}
    ref={me => this.sectionList = me}
    maxToRenderPerBatch={20}
  />

This is my getItemLayout function:

 getItemLayout = (
  data,
  index,
 ) => {
   const layoutTable = layoutTableGenerator(data, 100, 40)

   return {length: layoutTable[index].length, offset: layoutTable[index].offset, index}
  }

and this is my helper function to generate data for getItemLayout:

 module.exports = (sections, itemHeight, sectionHeaderHeight, sectionFooterHeight = 0) => {
   return sections.reduce((layoutTable, section, sectionIndex) => {
     const layoutTableLastItem = layoutTable[layoutTable.length - 1]
     const currentSectionLayoutTable = []

     currentSectionLayoutTable.push({
       length: sectionHeaderHeight,
       offset: layoutTableLastItem ? (layoutTableLastItem.offset + layoutTableLastItem.length) : 0
     })

     for(let i = 0; i < section.data.length; i++) {
       const currentSectionLayoutTableLastItem = currentSectionLayoutTable[currentSectionLayoutTable.length - 1]

       currentSectionLayoutTable.push({
         length: itemHeight,
         offset: currentSectionLayoutTableLastItem.offset + currentSectionLayoutTableLastItem.length
       })
      }

      const currentSectionLayoutTableLastItem = currentSectionLayoutTable[currentSectionLayoutTable.length - 1]
      currentSectionLayoutTable.push({
        length: sectionFooterHeight,
        offset: currentSectionLayoutTableLastItem.offset + currentSectionLayoutTableLastItem.length
      })

     return [
       ...layoutTable,
       ...currentSectionLayoutTable
     ]
  }, [])
 }
1 Answers

That's because SectionList has headers which need to be accounted for when using getItemlayout. This Link describes it in detail and also links an npm package as a solution

Related