Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Tailwind class as a prop in React

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

like image 679
Ahmad Malik Avatar asked May 01 '26 09:05

Ahmad Malik


1 Answers

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")}
/>