4

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.

sd_dewasurendra
  • 383
  • 6
  • 22

2 Answers2

5

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.

Jonny
  • 285
  • 2
  • 11
0

You could add a section footer component in which you will render your empty screen based on section.data.length

For a little example see this

  • Thank you @Alexandru for the your answer. If I use like that it will gives each view for each empty section. So in my case it gives 3 views – sd_dewasurendra Jul 26 '19 at 14:17