Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React native list empty component not working in section list

I am trying to render empty component when my sections are empty. This is the sample code of mine

<SectionList
    sections={[
        {title: 'sectionOne', data: this.props.Activities.ActivityTypeOne},
        {title: 'sectionTwo', data: this.props.Activities.ActivityTypeTwo},
        {title: 'sectionThree', data: this.props.Activities.ActivityTypeThree}
    ]}
    keyExtractor={ (item, index) => index }
    stickySectionHeadersEnabled={true}
    extraData={this.state}
    ListEmptyComponent={this.renderEmptyScreens}
    />

But when this 3 all arrays are empty, it does not trigger the ListEmptyComponent Can anyone tell me what is wrong with this code, or if my logic is incorrect can anyone please explain me. Bacically I need to render some view when all 3 arrays are empty.

like image 893
sd_dewasurendra Avatar asked Oct 26 '25 18:10

sd_dewasurendra


1 Answers

After running into this problem myself, I discovered that the sections property has to be completely empty for the list to be considered empty (aka, sections itself should equal to []).

Solution:

Use a ternary operator to choose what to pass into sections based on your own criteria. If it's decided to be empty, pass in [], else pass in your sections object. As an example, your code would look something like this:

isSectionsEmpty(sectionsObject){
    //logic for deciding if sections object is empty goes here
}

render(){
    /* ...
       Other render code
       ...
    */
    const sections = [
        {title: 'sectionOne', data: this.props.Activities.ActivityTypeOne},
        {title: 'sectionTwo', data: this.props.Activities.ActivityTypeTwo},
        {title: 'sectionThree', data: this.props.Activities.ActivityTypeThree}
    ]
    return(
        ...
        <SectionList
            sections={this.isSectionsEmpty(sections) ? [] : sections}
            keyExtractor={ (item, index) => index }
            stickySectionHeadersEnabled={true}
            extraData={this.state}
            ListEmptyComponent={this.renderEmptyScreens}
            />
        ...
    )
}

Note: You could also forego the ternary operator and directly return either your sections object or [] from isSectionsEmpty, but this method allows for you to check if sections is "empty" elsewhere in your code, if needed.

like image 68
Jonny Avatar answered Oct 29 '25 07:10

Jonny