#Tailwind in Astro map function.

1 messages · Page 1 of 1 (latest)

pastel night
#

Hi there: Anyone knows how to get Tailwind to work in Astro loops? Currently, it doesn't seem to work — the classes are emitted but not picked up by Tailwind.

past tusk
#

A code sample of what you're trying to do would be nice.
From #general you had:

{
  pricing.data.map(p => (
    <div class="border-${p.theme}-500">
      ... 
    </div>
  ))
}

You can't use variables to construct class names with Tailwind. Tailwind goes through your class attributes and generates the CSS based on the class names it finds. From Tailwind's point of view, border-${p.theme}-500 is not a class name it recognizes.

What you could do in this particular case, is add your own custom colors to Tailwind, then you can just have border-theme-500
https://tailwindcss.com/docs/customizing-colors#adding-additional-colors

Customizing the default color palette for your project.

pastel night
#

The colour has already been added. The problem is the dynamic generation. Theoretically, it should be possible — but provided Astro generates the HTML before Tailwind picks up on it.

#

Right now it seems like there's more of a static analysis of the input files.

past tusk
pastel night
#

Oh well, too bad then.

past tusk
#

All you have to do is move the code into the frontmatter:

---
...
const bgColor = `border-${p.theme}-500`
---

{
  pricing.data.map(p => (
    <div class:list={["text-bold", {bgColor}]}>
      ... 
    </div>
  ))
}

Note: not tested

pastel night
#

Tested, doesn't work unfortunately.

#

There's an alternate way to make them work — that's to create classes around that use these variables.

#

So in the example below, if border-green-500 exists somewhere else, the class will be generated and it will work.

<div class="border-green-500"> Elsewhere... </div>

{
  pricing.data.map(p => (
    <div class="border-${p.theme}-500">
      ... 
    </div>
  ))
}
past tusk