#React + Tailwind updating classes

3 messages · Page 1 of 1 (latest)

severe grove
#

Hey, I've got this code:

<div className={`grid grid-cols-${cols} gap-${gap}`}>
    {renderGrid()}
</div>```

The cols and gap are both useState's, which update at runtime, but tailwind doesn't seem to work with this class declaration. 

Anyone knows how I can fix this?

TS config:
```TS
/** @type {import('tailwindcss').Config} */
export default {
    content: ['./src/**/*.{astro,html,js,jsx,md,mdx,svelte,ts,tsx,vue}'],
    theme: {
        extend: {},
    },
    plugins: [],
}```
charred heraldBOT
#

Hi @severe grove. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Based on the information provided in the extracts, it seems like you're encountering a limitation of Tailwind CSS itself. Tailwind requires you to use the full class name in your file so that it knows which classes to add to your CSS bundle. This is documented in the Tailwind CSS documentation here (https://tailwindcss.com/docs/content-configuration#dynamic-class-names).

In your case, you're trying to dynamically generate class names using template strings in JavaScript, which Tailwind doesn't support. This is because Tailwind can't predict what the final class name will be at build time.

One workaround suggested in the extracts is to create a map of your class names and apply them like this:

---
// src/components/Text.astro

const sizes = {
  xl: 'text-xl',
  2xl: 'text-2xl',
  3xl: 'text-3xl',
};

const { size } = Astro.props;
---
<div class={sizes[size]}>
  Text of different sizes!
</div>

In your case, you could create a similar map for your cols and gap values and use that to apply the correct classes.

Please note that this information is based on the Astro framework and Tailwind CSS integration. If you're using React, the implementation might be slightly different but the concept should be the same.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: