41

In React Native, I have a static array of books that I map over and output in stacked rows like this:

return books.map((book, i) => {
  return(
    <View style={styles.book} key={i}>
      <Text style={styles.book}>{book.title}</Text>
    </View>
  );
});

I also have a bottom border on each book via styles.book:

book: {
  borderBottomWidth: 1,
  borderBottomColor: '#000000'
}

I need the last book in the list to NOT have a bottom border, so I'll need to apply borderBottomWidth: 0 to it I think? In React Native, how can I get the last book in the list to not have that bottom border? (In normal css we'd use last-child)

2
  • I dont know react but bottom does not come at the end? like borderWidthBottom?
    – YOU
    Commented May 16, 2016 at 1:30
  • books[books.length - 1] is last one in javascript
    – YOU
    Commented May 16, 2016 at 1:32

2 Answers 2

64

You could achieve this using some logic:

return books.map((book, i) => {
  return(
    <View style={ (i === books.length - 1) ? styles.noBorderBook : styles.book} key={i}>
      <Text style={(i === books.length - 1) ? styles.noBorderBook : styles.book}>{book.title}</Text>
    </View>
  );
});

What this does is check if i, the iterator, is equal to the books array's length - 1.

1
  • 2
    Thank you, works great, just added the - 1 to match the last key!
    – Wonka
    Commented May 16, 2016 at 14:25
16

You can try extended-stylesheet that supports :last-child:

import EStyleSheet from 'react-native-extended-stylesheet';

const styles = EStyleSheet.create({
  book: {
    borderBottomWidth: 1,
    borderBottomColor: '#000000'
  },
  'book:last-child': {
    borderBottomWidth: 0
  }
});

return books.map((book, i) => {
  const style = EStyleSheet.child(styles, 'book', i, book.length);
  return(
    <View style={style} key={i}>
      <Text style={style}>{book.title}</Text>
    </View>
  );
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.