05. Derive RGB channels with JS
🐇 TL;DR
- We moved out CSS variables to the plugin
- The
R
G
B
format we’re using is a bit uncommon - Our original color themes were using
HEX
values - Let’s use JavaScript to convert
HEX
colors to the desiredR
G
B
format!
🐢 Background
We’ve moved our CSS variable declarations from the CSS file to the plugin. This is great, we’re now doing all our work in the same file - and in the same language!
Looking at our code, it’s kinda odd that we’re defining the CSS variables with this R
G
B
channels format. It’s… uncommon.
We want our plugin to end up being reusable without much manual work. And converting the colors to R
G
B
channels sounds like manual work!
Remember our initial color themes objects we started the workshop with? Click below to show the code snippet.
const themes = {
base: {
50: '#eef2ff',
100: '#e0e7ff',
200: '#d0d7f7',
300: '#aab9ff',
400: '#8994ff',
500: '#6b70fc',
600: '#554fee',
700: '#453ccd',
800: '#3830a2',
900: '#272173',
},
rainforest: {
50: '#ecfdf4',
100: '#c9f2de',
200: '#9de9c6',
300: '#56d0a0',
400: '#00b380',
500: '#009268',
600: '#007955',
700: '#006344',
800: '#005038',
900: '#003422',
},
candy: {
50: '#fdf2f8',
100: '#f7e2ee',
200: '#f8cce5',
300: '#f5a4d0',
400: '#f271b5',
500: '#e13d90',
600: '#c31667',
700: '#a1004b',
800: '#84003d',
900: '#590028',
},
}
Those were using HEX
color values.
It will be much more common to deal with HEX
colors than our custom R
G
B
format.
For example, if someone was to import the color palette from Tailwind CSS (via tailwindcss/colors
), they’d get… HEX
values.
Let’s assume our plugin should take HEX
colors as an input. Since we’re now working in JavaScript, we can write some code to transform HEX
values into our desired, custom R
G
B
format.
We could probably do this from scratch, but there’s a little library by Sindre Sorhus called hex-rbg that I really like.
As the name suggest, it converts HEX
colors to useful RGB
formats.
Let’s use that to create a little helper function that takes a HEX
value, and returns our desired R
G
B
string:
const hexRgb = require('hex-rgb')
function getRgbChannels(hex) {
const { red, green, blue } = hexRgb(hex)
return `${red} ${green} ${blue}`
}
If we were to call that function with the #0099aa
HEX
color, here’s what we’d get:
getRgbChannels('#0099aa') => 0 153 170
Perfect!
We can use this function to transform the HEX
values from our color themes object.
🏆 Your challenge 🏆
In the Tailwind Play below:
- In the Config tab, Use the
getRgbChannels
helper function to transform theHEX
values from thethemes
object.
You know the drill - code duplication is still okay for now 😅
✌️ Good luck!
Start challenge