Loop colors array in React styled components
Very quick guide how to loop colors array in React styled components.
Problem
You have a list of sections in your document, you want each to have a different color from array.
Solution
Note: This tutorial is done using styled-components package but with easily work with other method for using styled components
Setting up styled components
You can skip to next section if you know how to do this
I use styled-components package. Install it in your React project:
npm i styled-components
Having dependency installed, let’s set up the HTML section component as our first styled component. Create a folder Section in your project and inside two files: index.jsx
and useStyle.jsx
.
Let’s start with useStyle
. Import styled components and set up the export.
See that styled
object has section
as one of optional properties. In `` you can set up a string attached to this section, where you list your CSS styles for this component. We will export the object under the name useStyle
.
In index.jsx
let’s use the styled section as follows:
We import useStyle
as StyledSection
(for naming purposes). We return the StyledSection
as a wrapper to all Section
component’s contents.
That’s it. Now whenever you will use Section
component, it will be wrapped with styled defined for it!
Setting up colors loop
Choose your colors and save them in an array. I chose my sample colors from coolors tool with I adore.
Now in the useStyle.tsx
let’s set up colors loop for background of our sections. We would like to have every section to have a different background color. Normally you would do it with a simple CSS :nth-child()
declaration, setting each color to a different section. But, this is programming, and in programming we want to be as lazy as possible.
Let’s write a small function returning a n section with n color from an array.
So far so good. Now let’s create a loop that adds this :nth-child
definition for every color of the array.
What is function does it basically concatenates string with CSS declaration, swapping n value as many times, as long the colors array is. The function returns a CSS string, that we can now easily inject into styled component declaration:
You can now use your sections in document flow and do not worry about their styling:
That it! Enjoy your looped colors now :)
Wanna see code in action? Check GitHub repository with whole project.