Ahmad Malik
Ahmad Malik

Reputation: 161

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

Upvotes: 10

Views: 19516

Answers (3)

Jon Catmull
Jon Catmull

Reputation: 12772

Using tailwind-merge and clsx packages you can achieve this:

Create a utility cn function like this and then import this wherever you need to use it.

import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";

export function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs));
}

Use it like this:

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

Upvotes: 1

Hamid
Hamid

Reputation: 1

try to pass it like this

className={bg-['${primary}'] ....}

Upvotes: -1

user12417761
user12417761

Reputation:

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

Upvotes: 6

Related Questions