cssreactjstailwind-css

Tailwind CSS classes show up in the DOM, but the styles are not being applied


I'm having issues when dynamically assigning text colors to some headings. I have a .map function that runs and outputs some divs with different heading colors. This is example of my code:

    {nftInfo.map((nft, index) => (
          <div
            className="flex flex-col space-y-3 rounded-lg border-2 border-opacity-25 bg-white p-5 hover:bg-slate-50 dark:border-slate-500 dark:bg-gray-700"
            key={index}
          >
            <div
              className={`flex justify-center space-x-4 font-bold text-${nft.color}-600 dark:text-${nft.color}-400`}
            >
              <div className={`text-lg  `}>
                {nft.title} {nft.color}  <--- This outputs the correct color
              </div>
              {nft.icon}
            </div>
    </div>

Example of JSON:

    {
          title: 'Dummy text 2',
          description: 'Lorem ipsum dolor sit amet consectetur adipisicing elit. Maxime minima odit aspernatur aliquam deleniti in corporis omnis cupiditate optio, voluptatum quasi reiciendis dolor, nostrum nihil quaerat est, doloremque mollitia possimus.',
          bottomText: 'Lorem ipsum dolor sit amet consectetur adipisicing',
          buttonText: 'Generate contract',
          icon: <CodeIcon className="mt-1 h-6 w-6" />,
          color: 'pink'
    }

Here you can see that I'm assigning text colors depending on the color I set in the JSON above.

text-${nft.color}-600 dark:text-${nft.color}-400

I can also see the string being correctly assigned in the developer tools DOM view, but when I check the CSS in the dev tools the style is not applied...

enter image description here enter image description here

Also, if I manually add the class to the div the heading does get colored...


Solution

  • The CSS file generated by Tailwind will only include classes that it recognizes when it scans your code, which means that dynamically generated classes (e.g. text-${nft.color}-600) will not be included.

    To ensure that your colors are added to the CSS, you could add safelist in tailwind.config.js that holds all of the color utility classes that you need (see https://tailwindcss.com/docs/content-configuration#safelisting-classes).

    module.exports = {
      ...
    
      safelist: [
        'text-pink-600',
        'dark:text-pink-400',
      ]
    }
    

    Another solution is to add the utility classes in an object in your component, so that they get picked up and added to the stylesheet when Tailwind parses your code. You can then look up the colors using your nft.color variable. For instance:

    const colors = {
      "pink": { 
        "light": "text-pink-600",
        "dark": "dark:text-pink-400",
      },
      ...
    }
    
    <div className={`${colors[nft.color].light} ${colors[nft.color].dark}`} />