开发者

Conditionally set background color in React component with Tailwind CSS

I am trying to use a hex color code passed through props to set the background color of a div. These are one-off colors that are generated dynamically, so cannot be added as a theme extension in tailwind.config.

I thought a template literal would be the best way to achieve this, but have not been able to get this to work with arbitrary color values in Tailwind CSS.

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 bg-[${color}]`}
      ></div>
      <p className="text-center">{color}</p>
    </div>
  );
};

export default ColorSwatch;

Pasting the hex color code dire开发者_如何学运维ctly into the className list produces expected results, but trying to use the prop value in a template literal results in a transparent background (no background effect applied).

Looking for advice on how to correct this or different approaches to dynamically setting background color with a hex code passed through props.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜