0

I am trying to find a smarter way to loop through an array and generate jsx and return to the render function:

  renderCardImages = () => {
    const cards = [
      'Visa',
      'MasterCard',
      'AmericanExpress',
      'Discover',
      'JCB',
    ]
    return (
      <View style={{ flexDirection: 'row' }}>
        <Image source={getCardIcon('Visa')} size={65} />
        <Image source={getCardIcon('MasterCard')} size={65} />
        <Image source={getCardIcon('AmericanExpress')} size={65} />
        <Image source={getCardIcon('Discover')} size={65} />
        <Image source={getCardIcon('JCB')} size={65} />
      </View>
    )
  }

  render () {

    return (
     {renderCardImages()}
    )
  }

How do I achieve this? I believe render is called only once.

Ackman
  • 1,562
  • 6
  • 31
  • 54

2 Answers2

2
return (
  <View style={{ flexDirection: 'row' }}>
    {card.map(c=>((<Image source={getCardIcon(c)} size={65} />))}
  </View>
)
bknights
  • 14,408
  • 2
  • 18
  • 31
1

Move the list of cards outside of the component if it's static, or get it from props if it's dynamic. Use Array.map() in the render function to iterate the list, and render the cards:

render () {
  return (
   <View style={{ flexDirection: 'row' }}>
      {cars.map(card => (
        <Image source={getCardIcon(card)} size={65} />        
      ))}
   </View>
  )
}
Ori Drori
  • 183,571
  • 29
  • 224
  • 209