Search code examples
reactjsfunctiontailwind-css

How can I added function in tailwindcss class


I want to added a function to tailwindcss class. such as, I have a list Tags. And I want to added a function as like as class. But it not work My function Name randomColor randomColor function i want to add as like tailwindcss class

My code is

{task?.tags?.length > 0 &&
                      task?.tags?.map((tag) => (
                        <li key={tag}>
                          <span
                            className={`inline-block h-5 whitespace-nowrap rounded-[45px]  px-2.5  text-sm capitalize text-[#F4F5F6]  bg-[${**randomColor()**}]`}
                          >
                            {tag}
                          </span>
                        </li>
                      ))}

My function is,

const bgColor = [
    "#0B956C",
    "#1C6FBD",
    "#BC1C1E",
    "#8D4615",
    "#0695B7",
    "#6110A7",
    "#99630F",
    "#14B9B2",
    "#99630F",
  ];

  export function randomColor() {
    const randomNumber = Math.floor(Math.random() * bgColor.length) + 1;
    const data = bgColor[randomNumber];
    if (data === undefined) {
      return bgColor[1];
    }
    return data;
  }

Please help me to solve this problem


Solution

  • **randomColor()** is incorrect JavaScript syntax. You may have meant randomColor() as in:

    <span
      className={`… bg-[${randomColor()}]`}
    >
    

    Furthermore, as per the documentation:

    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.

    If you use string interpolation or concatenate partial class names together, Tailwind will not find them and therefore will not generate the corresponding CSS:

    Don’t construct class names dynamically

    <div class="text-{{ error ? 'red' : 'green' }}-600"></div>
    

    In the example above, the strings text-red-600 and text-green-600 do not exist, so Tailwind will not generate those classes. Instead, make sure any class names you’re using exist in full:

    Always use complete class names

    <div class="{{ error ? 'text-red-600' : 'text-green-600' }}"></div>
    

    You could:

    • Have the entire class in the bgColor array like:
      const bgColor = [
        "bg-[#0B956C]",
        "bg-[#1C6FBD]",
        "bg-[#BC1C1E]",
        "bg-[#8D4615]",
        "bg-[#0695B7]",
        "bg-[#6110A7]",
        "bg-[#99630F]",
        "bg-[#14B9B2]",
        "bg-[#99630F]",
      ];
      
      <span
        className={`… ${randomColor()}`}
      >
      
      Also, ensure the file that the randomColor() function is in is covered by the content file globs in the Tailwind configuration.
    • Use the style attribute:
      <span
        className={`…`}
        style={{
          backgroundColor: randomColor(),
        }}
      >