Home > Net >  apply style when 2 adjacent items have different attribute
apply style when 2 adjacent items have different attribute

Time:06-06

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.

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?

CodePudding user response:

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
    }
}

CodePudding user response:

You can compare the group property using the i argument

const arr = [
    {"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}    
]

renderItem={({item, i }) => {
    return ( 
        <div className={arrOfObjects[i]?.group !== arrOfObjects[i 1]?.group ? "class-name" : undefined}>
            <SingleItem key={item.code} } product={item} />
        </div>
    )
}}
  • Related