Array wrapping with modulus

Recently came across a requirement that consisted of a list of items to display which is decorated by a smaller list of colours.

The colours were to cycle through and wrap at the end of the list — starting over from the beginning.

Mini Challenge 01: Changing Background Colors for Certificates Card

Story for the challenge

Suppose you’re creating a portfolio and want to showcase your certificates on one of the screens. In that case, you can make each certificate card visually appealing by giving it a different border color. To achieve this, you can apply an array of colors to the certificate cards in ascending order.

After considering how to implement a counter with boundary wrapping, I recalled a trick I’ve seen in the past… Wrap the array index via the use of a modulus operation:

{{ id, title, platform, date }, index) => (
    style={{ index % bgColors.length }} // !!

Using the modulus for this type of problem isn’t my invention, but I sure was pleased with myself when I was able to implement it for an elegant, one-line solution! (See the style={{ ... }} line.)

My solution in action:

My solution
A screenshot if the CodePen embeds cease working.

By admin

Linux admin, JS / React / Python / Perl developer.