4
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

TailwindCSSで動的なClassを設定するときに陥りがちなミス

Last updated at Posted at 2025-01-28

概要

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はビルド時に静的に検出可能な完全なクラス名にプロパティをマップするため
上記の記述であれば期待通りに動作する

4
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?