Loading
Tailwind Multi-Theme Strategy Workshop (16 exercises)
exercise

Convert Hex to RGB with JavaScript

Let's move our Tailwind plugin to its own file and improve the way we define colors in our themes.

We are now importing the plugin into our Tailwind config file:

Loading exercise

Transcript

0:00 Our plugin is going to continue growing going forward, so I went ahead and moved it to its own file. Looking at the tailwind.config file, you can see we're requiring this plugin file. At the bottom here, instead of defining the plugin, we pass the plugin that we've imported in this file.

0:15 If we look at the plugin file, there should be something bothering you at this point. We have a themes color in hex values. Then we define our colors as RGB separate channels, but we do it manually. We convert these manually. There is nothing that takes the values from these themes and then passes them there.

0:36 We can probably improve the situation here. First of all, the R, G, and B separate channels is not very common and kind of awkward. That would be much nicer if we could pass the colors as hex values. For example, if someone uses the Tailwind default colors imported from tailwindcss/colors, these would come as hex values.

0:53 Because we are now in JavaScript land, we can use a little JavaScript function that can take a hex value and do the transformation into the R, G, and B channels we want.

1:03 We could do this manually, but here I have provided a little helper function. This is a library by Sindre Sorhus called hex-rgb. I created this getRgbChannels function here that takes a hex value. It's going to grab the red, green and blue channels and return them as a string.

1:20 Your challenge here is to take all of these values here and replace them with this getRgbChannels function and grab them from the themes object instead. Once again, don't worry about code duplication and repetition. We'll sort that out later. For now, let's just focus on making the transformation from hex to RGB.