Home > Software engineering >  How can I find the first and last item in a React Native sectionList?
How can I find the first and last item in a React Native sectionList?

Time:08-30

I have a sectionList with sections. I want to find the first and last items in the entire list. So if the list has 10 items and 3 sections, I want to find the item at index 0 and find the item at index 9.

The purpose of this is that I want to style the first and last items in the entire sectionList and whatever logic I write ends up styling the first or last item between each section.

As a reminder, the sectionList renderItem method provides:

<SectionList 
   sections={data}
   renderItem={({item, index, section}) => {
      // How to access the first and last items in this entire List. Not just the first 
      // and the last item in between each section.
      <List.Item 
         title={item.title}
         style={{
            backgroundColor: 'gray',
         }}
       />
   }
/>

Here is an Expo Snack, that might be able to help get started on it. How do I make the first and last items in this sectionlist a different background color?

enter image description here

CodePudding user response:

There is no solution just by using SectionList properties. However, you can manage to do that by creating a simple function that checks if an element is the first or the last one across sections.

const isFirstOrLast = (index, section, globalData) => {
  return (index === 0 && section.title === globalData.at(0).title) ||
  (index === section.data.length - 1 && section.title === globalData.at(-1).title)
}

And do it like

<SectionList
        sections={DATA}
        keyExtractor={(item, index) => item   index}
        renderItem={({ item, index, section }) => {
          return <Item style={isFirstOrLast(index, section, DATA) ? { backgroundColor: "white" } : {}} title={item} />;
        }}
        renderSectionHeader={({ section: { title } }) => (
          <Text style={styles.header}>{title}</Text>
        )}
      />

As seen in this working example.

  • Related