Home > Mobile >  How to render conditionally based on alternating patterns?
How to render conditionally based on alternating patterns?

Time:10-17

I have a list of products that I want to display in a card view. The card background should go like this: Green, Blue, Red, Purple, Green, Blue, Red, Purple, etc etc

products.map(item => (
    <div style="background-color: {bgColor}"> 
       <h1>{item.name}<h1>
    </div>
    { bgColor === 'green'&& setBgColor('blue')}
    { bgColor === 'blue' && setBgColor('red')}
    { bgColor === 'red' && setBgColor('purple')}
    { bgColor === 'purple' && setBgColor('blue')}
))}

This code obviously doesn't work because it'll end up in a never ending loop.

But essentially I'd like the map function to consider what state the color is in, and for the NEXT render in the products array, change the color to a different color.

Logically, I'm trying to say the below code for each map item

if (bgColor === 'green') { 
   setBgcolor: 'blue'
   return
}
if (bgColor === 'blue') { 
   setBgcolor: 'red'
   return
}
if (bgColor === 'red') { 
   setBgcolor: 'purple'
   return
}
if (bgColor === 'purple') { 
   setBgcolor: 'green'
   return
}

I'm open to completely different methods of implementing this however..

CodePudding user response:

If I understood your issue correctly, you can create a map of colors based on the remainder when you divide the item index by 4.

This code should render 'blue' when the item's index is 0/4/8... etc.

const colorMap = {
 0: 'blue',
 1: 'red',
 2: 'green',
 3: 'purple'
}

products.map((item, index) => (
    <div style="background-color: {colorMap[index % 4]}"> 
       <h1>{item.name}<h1>
    </div>
))}
  • Related