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

Why am I unable to dynamically get tailwind colors from tailwind.config? (With SvelteKit)

I am trying to set tailwind classes dynamically, but ran into an issue where colors defined in tailwind.config.cjs won’t be loaded if I call them from a function. Here is a simplified example.

+page.svelte

<script>
    const getTeamName = () => {
        return 'team1';
    };
</script>

<div class={`bg-white text-teams-${getTeamName()}`}>Team 1</div>
<div class={`bg-white text-teams-team2`}>Team 2</div>

tailwind.config.cjs

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

const config = {
    content: [
        './src/**/*.{html,js,svelte,ts}',
        './node_modules/flowbite-svelte/**/*.{html,js,svelte,ts}'
    ],

    theme: {
        extend: {
            colors: {
                teams: {
                    team1: '#e2012d',
                    team2: '#826818',
                }
            }
        }
    },
    plugins: [require('flowbite/plugin')],
};

Screenshot of result

teams

You can see team2 color is loading just fine, but team1 stays black (The color code is bright red). What’s interesting is that if I set the getTeamName return value to ‘team2’, the color will load. It seems to have something to do with the colors having been loaded or not? Not sure if this is a sveltekit issue or tailwind issue.

>Solution :

It seems like the tailwind cannot scan the class, because the getTeamName() is a runtime variable

try use

const getTeamName = (team) => {
    // use a switch or if..else.. statement here

    return 'text-teams-team1';
};
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