Loading
Multi-Theme Tailwind 16 exercises
solution

Dynamically Adding Themes through Iteration

We're going to use the addBase function multiple times, once for each theme.

Our theme is an object containing multiple keys: base, rainforest, and candy.

To be able to iterate over them, we're going to keep the :root definition as is, but close the addBase function around it.

Its rol

Loading solution

Transcript

0:00 Here, we're going to use addBase function multiple times, once for each theme. If we look at our theme, we can see that it's an object that has multiple keys, base, rainforest, etc.

0:11 To be able to iterate over them, we're going to keep this root definition as is, but we want to close this addBase function here, and its role is going to just define the root scope variables, and then for our three theme scopes here, let's reopen another addBase just so the syntax is correct and things don't break.

0:31 Now instead of doing these three declarations manually, we're going to iterate over the themes object. Here outside of the addBase -- let me scroll up a bit -- I will go Object.entries and grab our themes. Then we can use a simple forEach loop here, and Object.entries will give us both the key and the values of the object. Essentially, we want to use an addBase function for each theme.

0:56 Here, we will copy the first CSS and JavaScript block and paste that here. Actually, before we continue, let's delete this one, because we want to make sure that we break things to fix them again later. Now everything is using the base color, which is what we're expecting. Let's try change the 500 to candy, and sure enough, that works.

1:17 We have access to the key, which is going to be base, rainforest, or candy, and then the value is going to be the object with the 50 to 900 shades.

1:25 First thing we want to change is here, the name of the theme. We'll want to do this dynamic, so I'll change this to a template string, and here, I can use interpolation to use the key. This is not valid JavaScript syntax. If you want a dynamic key in an object, you need to wrap it in square brackets as well like so.

1:47 Now we're generating the correct data, theme scopes, but we need to update the value to be the correct theme. Essentially, themes.base here can be replaced with the value, which is going to be one of these objects. Cross our fingers and save, and boom, everything is working again.

2:05 Once again, we're one step closer to accepting user-defined themes input. There's still hard-coded stuff in there, but we've just taken one step in the right direction.