Search code examples
react-nativereact-native-iosreact-native-flatlistreact-native-sectionlist

How to render SectionList with Nested looped of Objects in data


I have the below json structure

{
  "title": "Name(s)",
  "type": "Text",
  "data": [
    {
      "source": "DB",
      "title": "All",
      "list": [
        {
          "name": "ABCD",
          "count": 1
        },
        {
          "name": "BCDE",
          "count": 1
        },
        {
          "name": "CDEF",
          "count": 1
        },
        {
          "name": "DEFG",
          "count": 2
        },
        {
          "name": "EFGH",
          "count": 1
        }
      ]
    }
  ]
},
{
  "title": "Category(s)",
  "type": "Text",
  "data": [
    {
      "source": "DB",
      "title": "All",
      "list": [
        {
          "name": "Vegetables",
          "count": 1942
        },
        {
          "name": "Saloon",
          "count": 355
        },
        {
          "name": "General Store",
          "count": 331
        },
        {
          "name": "Restaurants",
          "count": 130
        },
        {
          "name": "Fast Food",
          "count": 108
        }
      ]
    }
  ]
}

I am trying to show the data as Like

1st SectionHeader : "Name(s)"
1stRow: "ABCD"
2ndRow "BCDE"
3rdRow "CDEF"
.
.
.

2nd SectionHeader : "Category(s)" 1stRow: "Vegetables"
2ndRow "Saloon"
3rdRow "General Store"
.
.
.
Here, should I use SectionList/Flatlist/ Mix both of them to get the above result.

In flatlist/sectionlist I am getting the section header Names(s)& Category(s) in renderSectionHeader but in renderItem, How Can I loop the "list" array of objects. Kindly let me know


Solution

  • You have to update the data like the following,

    eg:

    [
      {
        "title": "Name(s)",
        "type": "Text",
        "data": [
          {
            "name": "ABCD",
            "count": 1
          },
          {
            "name": "BCDE",
            "count": 1
          },
          ...
        ]
      },
      {
        "title": "Category(s)",
        "type": "Text",
        "data": [
          {
            "name": "Vegetables",
            "count": 1942
          },
          {
            "name": "Saloon",
            "count": 355
          },
          ...
        ]
      }
    ...
    ]
    

    And use SectionList for display it,

    eg:

     ...
        <SectionList
          renderItem={({item, index, section}) => <Text key={index}>{item.name}</Text>}
          renderSectionHeader={({section: {title}}) => (
            <Text style={{fontWeight: 'bold'}}>{title}</Text>
          )}
          sections={this.state.data}
          keyExtractor={(item, index) => item + index}
        />
        ...