React Native) How can I add a margin between elements that are wrapped in a map function?

Viewed 238

I am trying to put a margin between card elements that are wrapped in a map function. What I want to do is like the link below:

enter image description here

Instead, what I currently have is without margin.

enter image description here

If I just simply put right margin to every card, I can't avoid going beyond the last card. I want to insert margin only between elements of the map function. Is there a way to make this possible?

Thanks in advance, and here is my code:

return (
<View onLayout={onLayout} style={styles.cardCarouselContainer}>
  <ScrollView horizontal={true} style={styles.scroll} showsHorizontalScrollIndicator={false}>
    {
      props.data.map(perf => (
        <TouchableOpacity onPress={() => {
          dispatch(selectTicker(perf.symbol));
          stackNavigation.navigate('Details', { companyName: findTranslation(perf.symbol), stockName: perf.symbol });
        }}>
          <Card key = {perf.symbol} symbol = {perf.symbol} close = {perf.close} changePercent = {perf.changePercent}/>
        </TouchableOpacity>
      ))

    }
  </ScrollView>
</View>

);

1 Answers

You can conditionally add the required margin in your map function by comparing the array length to the current index.

props.data.map((perf, index, arr) => (
    <TouchableOpacity onPress={() => {
      dispatch(selectTicker(perf.symbol));
      stackNavigation.navigate('Details', { companyName: findTranslation(perf.symbol), stockName: perf.symbol });
    }}>
      <Card key = {perf.symbol} symbol = {perf.symbol} close = {perf.close} changePercent = {perf.changePercent} style={arr.length !== index + 1 ? styles.styleWithMargin : styles.styleWithoutMargin}/>
    </TouchableOpacity>
  ))
Related