6

I am creating a reusable component button to which I want to pass two Tailwind classes as props and use them dynamically.

Here is my component:

function Button({ primary, secondry, label, onClick }) {
  return (
    <button
      onClick={(e) => onClick(e)}
      className={`bg-${primary} py-0.5 px-3 rounded text-white font-semibold text-xl border-2 border-${primary} hover:bg-${secondry} hover:text-${primary} cursor-pointer duration-300`}
    >
      {label}
    </button>
  );
}

This is how I am using the component:

<Button
label={"Cancel"}
primary="red-700"
secondry="zinc-900"
onClick={(e) => navigate("/customers")}
/>

However, the classes are not being applied. This is how it looks:

How button looks

Ed Lucas
  • 5,955
  • 4
  • 30
  • 42
Ahmad Malik
  • 117
  • 1
  • 1
  • 9
  • 1
    Tailwind does not support dynamic classes. This has been answered here: https://stackoverflow.com/questions/71937890/tailwind-css-classes-show-up-in-the-dom-but-the-styles-are-not-being-applied – Ed Lucas Apr 28 '22 at 16:43

1 Answers1

4

Try to pass the whole string bg-red-700 like this like this

function Button({ bgprimary, textprimary, borderprimary, bgsecondary, label, onClick }) {
  return (
    <button
      onClick={(e) => onClick(e)}
      className={`${bgprimary} py-0.5 px-3 rounded text-white font-semibold text-xl border-2 ${borderprimary} hover:${bgsecondary} hover:${textprimary} cursor-pointer duration-300`}
    >
      {label}
    </button>
  );
}

And use it like

<Button
label={"Cancel"}
bgprimary="bg-red-700"
textprimary="text-red-700"
borderprimary="border-red-700"
bgsecondary="bg-zinc-900"
onClick={(e) => navigate("/customers")}
/>