Quick Tip: Using Arrays as CSS config and Immutable Reverse
As it becomes more and more common to articulate our styles using Javascript, arrays can be a useful data structure to define common theme configurations like sizes, colours, breakpoints, etc…
For example, I will usually establish one or more config files that look something like this:
/**
* styles/config.js
*/export const scale = [
4, // Smallest
8,
16,
24,
32,
40, // Biggest
]export const shadesOfGrey = [
'#FAFAFA', // Lightest
'#F5F5F5',
'#EEEEEE',
'#E0E0E0',
'#BDBDBD',
'#9E9E9E',
'#757575',
'#616161',
'#424242', // Darkest
]
And I could use this in a React component (with styled-components) like so:
/**
* Button/index.js
*/import React from 'react'
import styled from 'styled-components'import { scale, shadesOfGrey } from '../styles/config'export const Button = styled.button`
padding: ${scale[0]};
background: ${shadesOfGrey[4]};
`
If you are new to styled-components, the above code should still be fairly readable. We are creating a button element and giving it padding and a background, the values for which are coming from the arrays we exported in our config file. The benefit to this technique is that you get all the methods on the Array.prototype to allow for a dynamic and functional approach to writing CSS styles using the values in those arrays.
A very simple example would be accessing the darkest shade of grey, even as we continue to add more greys to our config. This can be done using Array.prototype.reverse(), but what I didn’t realize initially is that this method mutates the original array. In the example below, both background and color will be the darkest grey.
export const DarkButton = styled.button`
padding: ${scale[1]};
background: ${shadesOfGrey.reverse()[0]};
color: ${shadesOfGrey[0]} // !!! MUTATED will be darkest !!!
`
A workaround is to wrap the reverse()’d in square brackets and spread its values out into this new array, like so.
export const DarkButton = styled.button`
padding: ${scale[1]};
background: ${[...${shadesOfGrey].reverse()[0]};
color: ${shadesOfGrey[0]} // still lightest! :)
`
Essentially this is just creating a copy of shadesOfGrey so that now the background is the darkest shade of grey and the color is still the lightest shade of grey.
I hope to write more about styled-components and how they are, in my opinion, a huge step forward in writing CSS for React and a natural evolution from my previous article about CSS modules. Stay tuned for that. Cheers!