何かやってみるブログ

興味をもったこと、趣味のこと、技術について色々書きます。

[メモ]tailwindcssでテンプレート文字列を使って動的にクラス名を割り当てられない。

ちょっと詰まったのでメモに残す。

例えば以下のような実装では背景色が反映されない。

https://tailwindcss.com/docs/background-color#arbitrary-values

import React from 'react';

interface Props {
  background: string;
}

const Component = ({background}: Props) => {
  return <div className={`w-4 h-4 bg-[${background}]`}></div>;
};

export default Component;

反映させるにはクラス名を明記する必要があるのでうまくマッピングしてあげる必要がある。

import React from 'react';

interface Props {
  background: string;
}

const Component = ({background}: Props) => {
  const backgroundMapping: { [key: string]: string } = {
    '#fff': 'bg-white',
    '#000': 'bg-blacka',
    '#f43f5f': 'bg-rose-500',
  };
  return <div className={`w-4 h-4 ${backgroundMapping[background]}`}></div>;
};

export default Component;

詳しくはdocumentに書かれている。

tailwindcss.com