Reputation: 431
I've got the following ActionButton.astro component:
---
interface Props {
buttonText: string;
buttonLink: string;
color: number;
outlined: boolean;
}
const { buttonText, buttonLink, color, outlined } = Astro.props;
// Define color and border classes based on the 'color' prop
const colorClass =
color === 1
? "primary"
: color === 2
? "secondary"
: color === 3
? "info"
: "light";
// Define the base button class
let buttonClass = `btn p-2 rounded-md font-medium`;
// Add background and hover classes based on 'outlined' and 'color' props
if (outlined) {
buttonClass += ` bg-transparent text-${colorClass} border border-${colorClass} hover:bg-${colorClass}`;
} else {
buttonClass += ` text-dark bg-${colorClass} hover:bg-${colorClass}-dark`;
}
---
<a class="nav-link" href={buttonLink}>
<button type="button" class={buttonClass}>
{buttonText}
</button>
</a>
When I pull this up in a dev server, the colors do not load correctly. It is not an issue with my color set up or anything, it has something to do with my browser or the dev server itself. Basically, out of the gate all the colors are just white. But when I go in and change the ${colorClass}
to primary
or secondary
or info
in the component file while the server is running, then it loads correctly and every other ActionButton component using that specific class also gets updated and loads the color correctly. This lasts until I restart the dev server, then it all goes to white again. Almost like it's being cached or something.
Any idea how I can get around this?
Upvotes: 0
Views: 599
Reputation: 1360
You can't create class names dynamically when using Tailwind. Tailwind doesn't run or execute any code, instead it reads the raw text from your files for class names. You can read more about it in the docs here: Dynamic Class Names
To get around this, you could use a pattern like this instead:
---
interface Props {
type: keyof classes;
}
const { type } = Astro.props
const classes = {
primary: "text-primary",
secondary: "text-secondary",
// ...
}
---
<div class:list={["bg-black", classes[type]]}></div>
Another option is to add all of classes inside your component to the safelist
property in your Tailwind config, although this is often not recommended. Safelisting Classes
Upvotes: 0