Home > Blockchain >  dynamic className with Tailwind in react
dynamic className with Tailwind in react

Time:12-21

I am making simple 'todo' project to improve my react skill one of it feature choosing the color of task card, but I can't figure out why my approach doesn't work. Here the code:

import React from "react";

const TaskCard: React.FC = () => {
  let color = "sky";
  return (
    <div>
      <div className="bg-white h-[80px] w-[100%] flex flex-row rounded-md">
        <div className={`p-1 bg-${color}-400`}></div>
      </div>
    </div>
  );
};

export default TaskCard;

this is just a sample of the code my problem is ${} doesn't work, it work when I hard code it.

CodePudding user response:

Using dynamic classes with Tailwind is not recommended because Tailwind uses tree-shaking. It means that any class that wasn't declared in your source files, won't be generated in the output file.

It would be best to use full class names when using Tailwind. From the docs about dynamic classes:

The most important implication of how Tailwind extracts class names is that it will only find classes that exist as complete unbroken strings in your source files.

As a last resort, Tailwind offers something called Safelisting classes. You can use safelist to include specific classes in your tailwind output file.

In your example, you can use regular expressions to include all the colors you want using pattern. You can force Tailwind to create variants as well:

module.exports = {
  content: [
    './pages/**/*.{html,js}',
    './components/**/*.{html,js}',
  ],
  safelist: [
    {
      pattern: /bg-(red|green|blue)-(400)/,
      variants: ['lg', 'hover', 'focus', 'lg:hover'],
    },
  ],
}

CodePudding user response:

I've used the following type of example code to good effect, you'll need to concatenate classes using clsx, I've been able to access some of the templates that come with Tailwind UI and they tend to do similar.

import React from 'react';
import clsx from 'clsx';

const TaskCard: React.FC<{ variant: string }> = ({ variant }) => {
  const variants: { [key: string]: string } = {
    sky: 'bg-sky-400',
    grass: 'bg-grass-400',
    fire: 'bg-fire-400',
  };
  return (
    <div>
      <div className="bg-white h-[80px] w-[100%] flex flex-row rounded-md">
        <div className={clsx('p-1', variants[variant])}></div>
      </div>
    </div>
  );
};

export default TaskCard;

You can build out your component variants with more classes too, if you want to see something a bit more in-depth, I wrote an article on this subject: https://morganfeeney.com/how-to/create-tailwind-component-variants-using-react

  • Related