react-nativeexporeact-native-flatlistreact-native-sectionlist

How to use nested flatlist or sectionlist?


I'm trying to create nested flatlist but an error occurres while rendering. I couldn't see any mistake. My array is like (contains semesters and lectures in that semester)

Array [
  Object {
    "semester": "1",
    "lectures": Array [
      Object {
        "grade": "BA",
        "id": 0,
        "lecture": "TÜRK DİLİ",
      },
      Object {
        "grade": "DC",
        "id": 2,
        "lecture": "FIZIKI",
      },
      Object {
        "grade": "AA",
        "id": 4,
        "lecture": "BİLGİSAYAR MÜHENDİSLİĞİNE GİRİŞ",
      },
      Object {
        "grade": "BB",
        "id": 6,
        "lecture": "MATEMATIKI Zorunlu сс 6 İNGİLİZCE",
      },
      Object {
        "grade": "DD",
        "id": 8,
        "lecture": "NESNEYE DAYALI PROGRAMLAMA",
      },
      Object {
        "grade": "AA",
        "id": 10,
        "lecture": "WEB TEKNOLOJİLERİ",
      },
    ],
  },
]

And my flatlist component:

<FlatList
    data={transcript}
    renderItem={({ item }) => (
      <View>
        <Text>{item.semester}</Text>
        <FlatList
          data={item.lectures}
          renderItem={({ item2 }) => (
            <View>
              <Text>{item2.lecture}</Text>
            </View>
          )}
          keyExtractor={(item2) => item2.id.toString()}
        />
      </View>
    )}
    keyExtractor={(item) => item.semester.toString()}
  />

Error that I get:

[Unhandled promise rejection: TypeError: undefined is not an object (evaluating 'item2.lecture')]

Anyway, <Text>HEY</Text> instead of <Text>{item2.lecture}</Text> works like expected.

When I use sectionlist like this

<SectionList
        sections={transcript}
        renderItem={({ item }) => <Text> {item.lecture}</Text>}
        renderSectionHeader={({ section }) => <Text>{section.semester}</Text>}
        keyExtractor={(item, index) => index}
      />

I get error

TypeError: undefined is not an object (evaluating 'items.length')

Solution

  • The issue here is that as per the official documentation the renderItem passes an object with three properties to the function - item, index, seperators. In the above code you are trying to de-structure a property called item2 which does not exist in the object as that property name is item. So to keep separate name for both the renderItem methods you can rename the second item to item2 using this syntax:

    renderItem={({ item: item2 })=>{}}

    This will allow you to rename the property to item2 and it will work fine. You can further read about renaming destructured variable here Renaming de-structured Variable