1
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】カスタム属性を用いて開閉用ボタンのopen時にスタイルを付ける

1
Posted at

はじめに

Tailwind CSSを用いたスタイリングで、ポップオーバー等を開閉するボタンの作成時に「ポップオーバーが開いている時にスタイルをつけたい」という場面がありました。

その際に試したことを書いていきます。

やりたいこと

通常時のスタイルが下記のようなボタンがあり、ボタンを押すとポップオーバーが出現します。

image.png

そのポップオーバーが出現している間(=ボタンが開いている状態)の時に下記のように枠線の色を変えたり文字色を変えたりすることを試みます。

image.png

やったこと

Tailwind CSSにはAdding custom stylesと呼ばれる、属性セレクタを指定してスタイルをつけられる仕組みがあるのでそれを利用します。

最初に該当のボタンにカスタムデータ属性を設定します。

今回の作業ではRadix UIを使っていたためボタン要素(Popover.Trigger)にdata-state属性がついています。

※Radix UI標準のButtonコンポーネントを使うとスタイルがつかなくなるため、今回はポップオーバー開閉のトリガーとして通常のbuttonタグを設定しています。

Popover.tsx
import { Box, Flex, Popover } from "@radix-ui/themes";

export default function CategoryAccordion() {
  return (
    <Popover.Root>
      <Popover.Trigger>
      // 見た目を規定する他のスタイルは説明に不要なため省略
        <button aria-expanded="true">
          カテゴリ
        </button>
      </Popover.Trigger>
      <Popover.Content>
        // ポップオーバーの中身が入ります
      </Popover.Content>
    </Popover.Root>
  )
}

このtsxで出力されるHTMLは以下のようになります。

<button aria-expanded="true" type="button"
 aria-haspopup="dialog" data-state="closed">カテゴリ</button>

上記のdata-state属性がボタンの開閉状態を定義しています。

ボタンが開いている時だけスタイルをつけたい場合、Tailwind CSSのAdding custom stylesを用いて以下のように指定します。

Popover.tsx
import { Box, Flex, Popover } from "@radix-ui/themes";

export default function CategoryAccordion() {
  return (
    <Popover.Root>
      <Popover.Trigger>
      // 見た目を規定する他のスタイルは説明に不要なため省略
      <button aria-expanded="true" 
          className="data-[state=open]:border-red-700 
                     data-[state=open]:text-red-700">
          カテゴリ
        </button>
      </Popover.Trigger>
      <Popover.Content>
        // ポップオーバーの中身が入ります
      </Popover.Content>
    </Popover.Root>
  )
}

今回はdata-state属性がopenの時だけ特定のスタイルをつけたいため、上記のようにすれば実現できます。

最後に

ここまで読んでいただきありがとうございます。

ボタンの開閉など、特定の条件下のみスタイルをつけたい場面はいくつか出てくるはずなのでこの記事がそういったケースでの助けになれば幸いです。

1
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
1
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?