09. Generate colors dynamically
š TL;DR
- Letās stop hard coding
primarycolor shades, and read values from the color themes instead. - We should support multi-level, nested color objects!
ā¬ļø Skip to the challenge
š¢ Background
Up to this point, weāve been assuming that we want to generate a primary color with 50 to 900 shades.
This assumption makes our plugin very ārigidā, and we cannot pretend this code is truly reusable.
What we need to do next is generate our CSS variables and color utilities based on what the themes actually contain.
We want to support multi-level color objects, where nested properties generate ākebab-caseā utilities.
Take the following theme object for the base theme:
const themes = {
base: {
primary: {
50: '#eef2ff',
100: '#e0e7ff',
200: '#d0d7f7',
300: '#aab9ff',
400: '#8994ff',
500: '#6b70fc',
600: '#554fee',
700: '#453ccd',
800: '#3830a2',
900: '#272173',
},
secondary: {
some: {
nested: {
color: '#0099aa',
},
},
},
},
// ...
}
Here, we explicitely ask for primary-50 to primary-900 colors within the primary key.
But we also demand a secondary key, with a ādeep nestedā color property.
Nested properties should generate kebab-case color keys, so in that case, hereās what CSS variable we should expect for the secondary color:
'--secondary-some-nested-color': getRgbChannels('#0099aa')
And the matching counterpart, where we extend the colors theme object in the config, should look like that:
secondary: {
some: {
nested: {
color: 'rgb(var(--secondary-some-nested-color) / <alpha-value>)'
}
}
}
Generating these CSS variables and theme extension objects dynamically based on the āinputā would make our plugin infinitely more reusable and versatile.
And we can use JavaScript to do this!
š Your challenge š
In the Tailwind Play below:
-
Write a JavaScript function that traverses a given object input, and generates the appropriate kebab-cased CSS variables.
Use that function to replace the āhardcodedā
primary-50toprimary-900CSS variables currently in place. -
Write a similar function that generates the appropriate colors extension object, and use that to replace the hardcoded
primaryobject currently extending the color theme in theconfig.
Youāll find more hints within the Play.
āļø Good luck!
Start challenge