概要
TailwindでCSSを指定しようといているときに下記のようにコードを書いていたところ、
例としてcolor
の場合以下のような挙動になった
- 文字の色がpropsで指定した色に変更されない
// importは省略
type Props = {
color: 'red' | 'blue'
text: string
}
export const SampleComponent: FC<Props> = ({ color, text }) => {
return (
<div className={twMerge('font-bold text-md', `text-${color}-500`)}>
{ text }
</div>
)
}
原因
下記ドキュメントに書かれている通り
https://tailwindcss.com/docs/detecting-classes-in-source-files#dynamic-class-names
Don't use props to build class names dynamically
(クラス名を動的に構築するためにプロパティを使用しないでください)
解決方法
公式通りに完全なクラス名で記述する
// importは省略
type Props = {
color: 'red' | 'blue'
text: string
}
const colorVariants = {
red: 'text-red-500',
blue: 'text-blue-500'
}
export const SampleComponent: FC<Props> = ({ color, text }) => {
return (
<div className={twMerge('font-bold text-md', colorVariants[color])}>
{ text }
</div>
)
}
Tailwindはビルド時に静的に検出可能な完全なクラス名にプロパティをマップするため
上記の記述であれば期待通りに動作する