Search code examples
javascriptcsstailwind-cssastrojs

How to apply TailwindCSS styles dynamically from a CMS?


I want to present categories on my article cards with different styles depending on the category itself. The styles are not applied if they come from the CMS, but if I add them statically, they are.

Here is my Categories.Astro file:

---
const {categories} = Astro.props
console.log(categories)
---

<div class="flex gap-2">
  {
    categories?.map((category: any) => (
      <div
        class={`${category?.style?.backgroundColor || ""} ${category?.style?.textColor || ""} ${
          category?.style?.hoverStyle || ""
        } text-xs font-bold uppercase px-3 py-1 rounded-full mr-1 mb-1 text-center flex justify-center items-center`}
      >
        {category?.name}
      </div>
    ))
  }
</div>

I tried with a React component in a Next.js project with the same approach as above to see if Astro was not working for me, but that didn't work either.

My added console.log (categories) provides me with all the data, and it does render the name of the categories on the page. This is an example of one of my categories:

 {
    _createdAt: '2023-02-22T08:08:32Z',
    _id: 'aba04de4-35e4-4b94-8499-e7070b838ef4',
    _rev: 'bjKRkMZtbKC9GgwKF3eReN',
    _type: 'category',
    _updatedAt: '2023-02-28T05:28:47Z',
    description: 'This category is all about Javascript.',
    name: 'Javascript',
    slug: { _type: 'slug', current: 'javascript' },
    style: {
      backgroundColor: 'bg-yellow-200 ',
      hoverStyle: 'hover:bg-yellow-300 hover:text-black',
      mainColor: 'text-yellow-200 ',
      textColor: 'text-black '
    }
  }

Here is what is rendered on the page. For instance, it should have had a background of `bg-yellow-200`:

enter image description here

If I inspect the element I get the following for the JavaScript category:

<div 
class="bg-yellow-200 text-black hover:bg-yellow-300 hover:text-black text-xs font-bold uppercase px-3 py-1 rounded-full mr-1 mb-1 text-center flex justify-center items-center">
   Javascript
</div>

Can you see what I'm doing wrong?

It seems like adding a safelist in the tailwind.config.js file is working, but it doesn't seem right. Is there a better way of making sure the styles get applied?


Solution

  • Tailwind does not parse or execute any code so it can't find the class names from your API

    You can use Safelisting or Raw content to get around this