In nextjs, I have a list of colors and a function that takes a number as an argument and returns a component styled by Tailwindcss that has a distinct color using that number.
const listColors = ["lime", "teal", "violet"]
function getStyle(idx: number) {
const color = listColors[idx % listColors.length];
return `bg-${color}-500 text-${color}-100`;
}
export default function TestComponent({text, idx} : {text: string, idx: number}) {
return (
<div className={getStyle(idx)}>
{text}
</div>
);
}
However, this code does not change the color of the component. I thought this was because the style was not a string literal, so I tried using the following code:
return 'bg-' + color + '-500 text-' + color + '-100';
This ended up not working too. However, if I explicitly write the color name, it works
return 'bg-teal-500 text-teal-100';
Why does explicitly writing the name of the color work while programmatically using the color does not?
>Solution :
Tailwind scans for unbroken strings to include for classes, so string interpolation doesn’t work
https://tailwindcss.com/docs/content-configuration#dynamic-class-names
For your case, you can replace the class generation with an object and keep the interface you had
const colorClasses = {
lime: "bg-lime-500 text-lime-100",
teal: "bg-teal-500 text-teal-100",
violet: "bg-violet-500 text-violet-100",
};
function getStyle(idx: number) {
const colorKeys = Object.keys(colorClasses);
const colorKey = colorKeys[idx % colorKeys.length];
return colorClasses[colorKey];
}