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.
https://www.codevertiser.com/quick-react-challenges-with-codepen-templates/
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:
{certificates.map(({ id, title, platform, date }, index) => (
<div
className='card'
style={{ index % bgColors.length }} // !!
key={id}
>
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: https://codepen.io/Ronald-Barnes/pen/RwqzpNR?editors=1011