Home > Back-end >  How would an alternate color pass every 4 elements to repeat the same component pattern with Array.m
How would an alternate color pass every 4 elements to repeat the same component pattern with Array.m

Time:12-16

I'm trying to send my child components in a reaction app an alternate color as a property, and I'm not really sure how to do it. The color of each CardSimpleRow component must alternate in 4 different colors and once the 4th color is there, it returns to the beginning of the color, let's say. I want to use map because my matrix is dynamic and writing each row of the matrix to render seems unnecessary.

export const FollowScreen = () => {
  const alternatingColor = [ ["#d72226", "#a8232a"], ["#123", "#a33a"], ["#f3f3f3", "#a8232a"], ["#dd26", "#a8232a"] ]
  return (
   <>
     {
       data.map((elements, index) => {
          return  <CardSimpleRow 
                     color={index % 4 ? alternatingColor[1] : alternatingColor[0]} 
                     elements={elements} 
                  />
       })
     }
   </>

  )

It's a gradient so I need to send the 1st array, then the 2nd array, then the 3rd, then the 4th and after that go back to the 1st array>

Example if there are 8 CardSimpleRow, I need 4 cards with the array from 0 to 4 and then the other four with the array from 0 to 4 again

CodePudding user response:

If I got it right, you need something like:

alternatingColor[0]
alternatingColor[1]
alternatingColor[2]
alternatingColor[4]
alternatingColor[0]
alternatingColor[1]
...

To obtain that you just need to change a single line:

...
color={alternatingColor[index % 4]} 
...

this will access the correct element in alternatingColor by taking the integer remainder based on the index.

Index 0 => remainder of 0 / 4 == 0
Index 1 => remainder of 1 / 4 == 1
...
Index 5 => remainder of 5 / 4 == 1

  • Related