1 year ago

#242465

test-img

pfinferno

Why is SectionList ref.current always undefined?

I am trying to use the scrollToOffset and scrollToIndex that SectionList provides. However, the SectionList ref I am using is always undefined when using ref.current.

In my class component I have the following:

private sectionListRef: any;

constructor(props: SampleScreenProps) {
    super(props);
    this.sectionListRef = null;
}

componentDidMount = (): void => {
    setTimeout(() => this.scrollToSection(), 2000);
};

scrollToSection = (): void => {
    
    // do some calculations to get the itemIndex and sectionIndex to scroll to

    this.sectionListRef.scrollToLocation({
        animated: false,
        itemIndex,
        sectionIndex,
        viewPosition: 0.5
    }); // this fails if the list is huge and the indices are far from the initial render location, and so moves on to onScrollToIndexFailed 
};

onScrollToIndexFailed = (error) => {
    // this.sectionListRef.current is always undefined in this function

    this.sectionListRef.current?.scrollToOffset({
        offset: error.averageItemLength * error.index,
        animated: true
    });
    setTimeout(() => {
        if (this.state.dataSet.length !== 0 && this.sectionListRef !== null) {
            this.sectionListRef.current?.scrollToIndex({ index: error.index, animated: true });
        }
    }, 10);
};

finally, here's the SectionList itself:

<SectionList
    inverted
    ref={(ref) => {
        this.sectionListRef = ref;
    }}
    sections={mappedSections}
    renderItem={this.renderItem}
    renderSectionFooter={this.renderSectionFooter}
    keyExtractor={(item, index) => index.toString()}
    keyboardShouldPersistTaps="never"
    keyboardDismissMode="on-drag"
    bounces={false}
    initialNumToRender={20}
    onScrollToIndexFailed={this.onScrollToIndexFailed}
/>

What is the cause of this?

Edit: I tried doing this.sectionListRef = React.createRef() in the constructor instead, but same result.

I understand scrollToOffset is part of SectionList, but the other two scroll functions are part of the underlying virtualized list, but it should still work the same as far as I know.

react-native

react-virtualized

react-ref

react-native-sectionlist

scrolltoindex

0 Answers

Your Answer

Accepted video resources