I have a Javascript App which is a playground for some UI Components made with TailwindCSS. These components are customizable (colors, background, etc).
For example, the user will be able to select a background color class from a dropdown (tailwind syntax - eg: bg-indigo-400
) and the selected class will be applied to the displayed UI component.
(All the classes are already generated in CSS by using safelist
option pattern in tailwind.config
).
The requirement:
To populate the select dropdown options, I need to generate an array of all the possible background color classes, as strings, based on current Tailwind Configuration Colors:
For example, if my Tailwind Config contains has:
theme: {
colors: {
brown: {
50: '#fdf8f6',
100: '#f2e8e5',
...
900: '#43302b',
},
primary: '#5c6ac4',
}
},
the available background color classes will be:
bg-brown-50
, bg-brown-100
.... bg-brown-900
, bg-primary
.
What I've tried
Based on this answer, https://stackoverflow.com/a/70317546/1135971, I was to able to get the available colors:
import resolveConfig from 'tailwindcss/resolveConfig'
import tailwindConfig from 'path/to/your/tailwind.config.js'
const fullConfig = resolveConfig(tailwindConfig)
console.log(fullConfig.theme.colors)
which gives me an object with the following format:
{
"brown": {
"50": "#fdf8f6",
"100": "#f2e8e5",
....
"900": "#43302b"
},
"primary": "#5c6ac4"
}
Now, based on this object, I'll need to generate all the background color classes, perhaps looping through all the properties of the object (Object.entries
) and generating the array of background color classes.
Is there any other approach? Maybe an exposed Tailwind function that I can import?
You can run your theme object through the util/flattenColorPalette.js
function, which will give you an object with all the possible colour suffixes as keys and theme colours as values:
import resolveConfig from "tailwindcss/resolveConfig"
import tailwindConfig from "path/to/your/tailwind.config.js"
import flatten from "tailwindcss/src/util/flattenColorPalette";
const fullConfig = resolveConfig(tailwindConfig)
const theme = fullConfig.theme.colors;
const flatPalette = flatten(theme);
const classes = Object.keys(flatPalette);
/*
* classes = [
* 'inherit', 'current', 'transparent', 'black', 'white',
* 'slate-50', 'slate-100', 'slate-200', 'slate-300', 'slate-400',
* …
* ]
*/
You can use either regexes (more formally correct) or String.prototype.endsWith
(probably easier to read for most) to filter the "inherit", "current" etc values out, and then do
classes.map(suffix => `bg-${suffix}`);