Search code examples
javascriptreactjsreact-nativereact-native-flatlist

Adding headers to FlatList


I have some data like this: data = [ {name: 'Christmans', date: '.....'}, {name: 'Easter', date: '.....'}, {name: 'Kwanza', date: '.....'} ...

I wanted to display the data with a sticky header like this:

-----[Upcoming]------------- Sticky section here

  • New Years Eve
  • Easter Monday
  • Easter Thursday
  • NASCAR raceday

[TODAY]

  • Christmas
  • Mikes birthday

[This week]

  • Joshes birthday
  • Earth day
  • 420 day

[Last week]

  • Mothers day etc

This is using a FlatList in react-native. How can I get the data formatted in that order? would I need to create 4 different flatlists and pass the upcoming data in the first one, today data in the second on etc? Would be nice to see an example. Thank you!


Solution

  • Use Section List instead of Flatlist

     <SectionList
        renderItem={({ item, index, section }) => (
          <Text key={index}>.{item}</Text>
        )}
        renderSectionHeader={({ section: { title } }) => (
          <Text style={{ fontWeight: "bold" }}>{title}</Text>
        )}
        sections={[
          { title: "Title1", data: ["item1", "item2"] },
          { title: "Title2", data: ["item3", "item4"] },
          { title: "Title3", data: ["item5", "item6"] },
        ]}
        keyExtractor={(item, index) => item + index}
      />
    

    For more details check this link - https://facebook.github.io/react-native/docs/sectionlist