Conditionally set background color in React component with Tailwind CSS

Unfortunately, Tailwind requires the color to be hardcoded into the className prop as it cannot compute arbitrary styles from dynamic className values.

Your best bet would be to set the background color using the style prop as shown below;

interface Props {
  color: string;
}

const ColorSwatch = ({ color }: Props) => {
  return (
    <div className="flex flex-col gap-1 p-2">
      <div
        className="h-20 w-20 border border-gray-400 shadow-md"
        style={{backgroundColor: color}}
      ></div>
      <p className="text-center">{color}</p>
    </div>
  );
};

export default ColorSwatch;

You can look here and here to read more on how Tailwind generates arbitrary styles.

Leave a Comment