Pro Tailwind

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 desired R G B format!

⬇️ Skip to the challenge


🐢 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.



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:

  1. In the Config tab, Use the getRgbChannels helper function to transform the HEX values from the themes object.

You know the drill - code duplication is still okay for now 😅


✌️ Good luck!

Start challenge