Iterate over a color array with help of a modulo operation
A quick little tip if you are using Styled Components in React and want to iterate over a color-array. Usually you don’t know how many elements you will iterate over, but you want to be sure that your color array starts over again if you have specified fewer colors than elements. Here is an example:
Let’s say we have this array of 5 different colors:
const colorArray = ["#24BC9D", "#FFAB00", "#3798DA", "#E64C3C", "#9A59B5"];
And lets say that we have an array with 11 numbers in called anArray
. We then iterate over this array and use modulus with the index of our number-array together with the index of our color-array to pass the HEX-code down to our styled component. Wow that was a long, complicated sentence. Let’s look at this code example instead:
{anArray.map((item, index) => (
<Example
key={item}
color={colorArray[index % colorArray.length]}
/>
)}
What this basically does is for each time we iterate through anArray
it takes the index of our current item and calculates which item in our color-array it should pass down. And when it comes to the bottom of your color-array it starts at the beginning again. So basically we’re saying this on our first iteration: color={colorArray[0 % 5]}
. This is the same as saying: color={colorArray[0]}
. This is again the same thing as saying color="#24BC9D"
to our styled component. So the only thing left for us to do is to pass down that prop to our styled component like this:
const Example = styled.div`
background-color: ${(p) => p.color};
`;
How does this work?
The modulus operator (%) calculates the remainder of two numbers. It’s a kind of repeated subtraction. This StackOverflow answer is the best I’ve seen to explain this:
In fact, with a % b you’ll ask yourself: What number remains if I repeat subtracting b from a until that operation is no longer possible?
So in our case if the array we’re .mapping ( anArray
) has 11 elements and our colorArray has 5 elements the computer does something like this on the last element:
- Can I subtract 5 from 11? Yes, result is 6.
- Can I subtract 5 from 6? Yes, result is 1.
- Can I subtract 5 from 1? No, final result is 1.
If you want to see all the calculations for each element
0 % 5 = 0 =colorArray[0]
1 % 5 = 1 =
colorArray[1]
2 % 5 = 2 =
colorArray[2]
3 % 5 = 3 =
colorArray[3]
4 % 5 = 4 =
colorArray[4]
5 % 5 = 0 =
colorArray[0]
6 % 5 = 1 =
colorArray[1]
7 % 5 = 2 =
colorArray[2]
8 % 5 = 3 =
colorArray[3]
9 % 5 = 4 =
colorArray[4]
10 % 5 = 0 =
colorArray[0]
11 % 5 = 1 =
colorArray[1]
You can see a full example here