Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Programmatically changing colors doesn't work

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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];
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading