Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have different style for items at certain locations in a list in React Native?

I'm trying to have different styles for the first and last items in a list, like the picture below:

enter image description here

Where the first card has rounded corner on the upper right and the last card has rounded corner on the lower right. I'm still figuring out how to approach this.

Is there any way to pass the location of an item in the list to the item itself so it can be applied to a different style? Or there are other better approaches?

Also, I would like to have the card to have both rounded upper and lower right corners if there's only one card present, like below:

enter image description here

like image 492
bleepmeh Avatar asked Dec 06 '22 13:12

bleepmeh


1 Answers

When rendereing items with ListView/FlatList/SectionList rendering method has index parameter. You can use that index to figure out if the item is first or last and give conditional styling for that item.

Example

renderItem = ({item, index}) => {
  if (index === 0) return <ListItem style={styles.firstItem} data={item} />
  else if (index === (this.state.data.length -1)) return <ListItem style={styles.lastItem} data={item} />
  else return <ListItem style={styles.item} data={item} />
}

render() {
  return <FlatList data={this.state.data} renderItem={this.renderItem} />
}
like image 146
bennygenel Avatar answered May 21 '23 09:05

bennygenel