Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

apply style when 2 adjacent items have different attribute

I have an array of objects like:

{"code": 123, "description": "Item 1", "group": 2},
{"code": 211, "description": "Item 2", "group": 2},
{"code": 234, "description": "Item 3", "group": 3},
{"code": 255, "description": "Item 4", "group": 4},
{"code": 311, "description": "Item 5", "group": 4},

I have a FlatList

<FlatList
data={products}
...
renderItem={({item, i }) => {
return <SingleItem key={item.code} } product={item} />
}}
/>

I rendered the list with FlatList and I want to apply a style to a <SingleIem> if 2 adjacent items have different groups.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

e.g.

1) Items 1 & 2 have the same group -> no style will be applied.
2) Items 2 & 3 have different groups -> style will be applied to Item 3
3) Items 3 & 4 have different groups -> style will be applied to Item 4

and so on.

How can I achieve this?

>Solution :

If you already have an array of objects at hand and an index that means that you can compare the current index to the last index and check if the group property is the same for both. Place inside of the renderItem function and assign classes accordingly

renderItem={ (item, i) => {
      const isSameCategrory = arr[i]?.group === arr[i-1]?.group;
      // rest of code goes here
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading