Cannot read property 'length' of undefined | SectionList

177 Views Asked by At

I am trying to populate a section list with three sections. The first two will scroll horizontally and the last will scroll vertically. I believe the only way to do this is to have a FlatList nested inside the section, however, I am getting the above error.

SECTION LIST CODE

  <SectionList
    sections={sections}
    renderItem={({ item, section }) => {
      if (section.index === 0) {
        return renderCategories(section);
      } else if (section.index === 1) {
        return renderPopular(section);
      } else {
        return renderRecent(section);
      }
    }}
    stickySectionHeadersEnabled={false}
  />

RENDER CODE

const renderCategories = ({ section }) => {
    return (
      <FlatList
        data={section.items}
        horizontal
        renderItem={({ item }) => <CategoryCard item={item} />}
      />
    );
  };

  const renderPopular = ({ section }) => {
    return (
      <FlatList
        data={section.items}
        horizontal
        renderItem={({ item }) => <PopularOfferCard item={item} />}
      />
    );
  };

  const renderRecent = ({ section }) => {
    return <RecentOfferCard item={section.item} />;
  };

SECTION DATA

  const sections = [
    { index: 0, type: "categories", title: null, items: categories },
    { index: 1, type: "popular", title: null, items: popularOffers },
    { index: 2, type: "recent", title: "Recently Added", items: latestOffers },
  ];
1

There are 1 best solutions below

11
Gavara.Suneel On BEST ANSWER

You are directly passing the section property to the renderCategories, renderPopular, renderRecent functions and de-structuring it. It should be like below

  <SectionList
    sections={sections}
    renderItem={({ item, section }) => {
      if (section.index === 0) {
        return renderCategories({ section });
      } else if (section.index === 1) {
        return renderPopular({ section });
      } else {
        return renderRecent({ section });
      }
    }}
    stickySectionHeadersEnabled={false}
  />

Also please change the section format to below:

const sections = [{ index: 0, type: "categories", title: null, data: categories },
{ index: 1, type: "popular", title: null, data: popularOffers },
{ index: 2, type: "recent", title: "Recently Added", data: latestOffers },];