Home > Software engineering >  How to pass prop to variant in reusable component
How to pass prop to variant in reusable component

Time:04-21

Thats my first time when I am trying to create a reusable component similar to those from the ui framework. I use a tailwind for styling. I created button variants. Primary, secondary, destructive. It works fine. However, I would like to add the ability to select a component color. However, I can't find a solution or figure out how to pass the color to BUTTON_VARIANT.

How do I pass a color prop to BUTTON_VARIANT?

import classNames from "classnames";

type ButtonVariant = `primary` | `secondary` | `destructive`;
type ColorVariant = "slate" | "red";

interface Props {
  children: any;
  variant?: ButtonVariant;
  className: any;
  color: ColorVariant;
}

const BUTTON_VARIANT: { [key in ButtonVariant]: String } = {
  destructive: `text-white bg-red-500 hover:bg-red-600 capitalize font-semibold`,
  primary: `text-white bg-blue-500 font-semibold hover:bg-blue-600 capitalize`,
  secondary: `text-blue-500 bg-blue-100 font-semibold capitalize hover:bg-blue-100 hover:text-blue-700`,
};

export const Button = ({
  children,
  variant = "primary",
  className,
  color,
}: Props) => {
  return (
    <button
      className={classNames(
        className,
        `rounded py-2 px-4`,
        BUTTON_VARIANT[variant],
        className
      )}
    >
      {children}
    </button>
  );
};

Button.defaultProps = {
  className: "",
  variant: "primary",
  color: "blue",
};

CodePudding user response:

You need to take out all the classes referring to colors (background, border, text, etc) from the styles from BUTTON_VARIANT, and create a COLORS_VARIANT object. However, keep in mind this will likely render your variant property likely useless. It will make little sense having a primary button red, or a destructive button blue.

I suggest that if you wish to use color as a variant, switch your variant prop names to be color-agnostic, such as solid|transparent|outline, etc.

  • Related