7
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

React・Tailwind CSS で動的にclassを追加する方法【アクティブクラス】

Last updated at Posted at 2021-04-20

React・Tailwind CSSで動的にclassを追加する方法になります。
propsの値でstyleを変えたい場合やアクティブクラスに別途classを追加したい場合などに有効かと思います。

解説

import React from 'react'

const Home = ({ active }) => {
  const normalStyle = 'px-6 py-4 bg-gray-200' // デフォルトのclass
  const activeStyle = `${normalStyle} bg-red-200 text-red-900` // デフォルトのclassと追加したいclass
  const style = active ? activeStyle : normalStyle // どちらのスタイルを当てるかを判別

  return (
    <div className={style}>
      <h1>Hello</h1>
    </div>
  )
}

export default Home

まずはデフォルトのclassを定義しnormalStyleに代入します。
その後に文字列連結でclassを追加してactiveStyleを作ります。

あとは、propsの値の条件などでclassNameを変えることで、動的にclassを追加することができます。

7
9
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
7
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?