3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Astro で class:list を使って Tailwind CSS のクラスを追加ライブラリなしに整理する

Posted at

この記事の概要

Astro のスタイリングにおいて、class:listというディレクティブが用意されています。

これを上手く使って、Tailwind CSS のクラスを追加ライブラリなしに整理してみようという試みです。

複雑なスタイルを実現しないといけないのであれば Tailwind Variants などを使った方が良いと思いますが、例で紹介する程度であれば依存関係を増やさずとも良いのでは?と思って記事にしてみました。

ごく個人的な主張ですが、私は dependencies を少なめに抑えておきたいタイプです。

アップデート対応やライブラリ間の不整合を解消している時間などがあまり好きではなく、ちょっとした実装であればライブラリ無しに解消できないかな?と考えてしまいます。

そういった前提の記事である、とご理解いただけると幸いです。

環境

依存関係 バージョン
astro 4.9.2
tailwindcss 3.4.3

作るもの

prioritydirectionを受け取るコンポーネントを作るとします。

  • priorityにはprimary, secondary があり、それぞれにあわせてスタイルが変わる
  • directionにはhorizontal, vertical があり、それぞれにあわせてスタイルが変わる
  • props がどうであれ変わらない、ベースとなるスタイルもある

初期状態

以下のdivにスタイルを追加していきます。

---
type Props = {
  priority: "primary" | "secondary";
  direction: "horizontal" | "vertical";
};

const { priority, direction } = Astro.props;
---

<div>
  ...
</div>

ベースのスタイル

props に関わらず適用するクラスを登録します。

- <div>
+ <div
+   class:list={[
+     "flex text-lg p-4",
+   ]}
+ >
    ...
  </div>

class:list={[]}の書式で、配列としてクラスを登録できます。
中身が 1 つだけでも問題ないので、まずは共通部分を記載します。

props による変化の整理

class:listへ追記する前に、props による変化を整理しておきます。

今回は以下とします。

  • priority
    • primary なら bg-red-500 text-white
    • secondary なら bg-blue-100
  • direction
    • horizontal なら flex-row
    • vertical なら flex-col

これを、class:listに適用できるように書くと、以下のようになります。

  <div
    class:list={[
      "flex text-lg p-4",
+     { "bg-red-500 text-white": priority === "primary" },
+     { "bg-blue-100": priority === "secondary" },
+     { "flex-row": direction === "horizontal" },
+     { "flex-col": direction === "vertical" },
    ]}
  >
    ...
  </div>

マークアップ部分にクラスの記載がたくさん入って長くはなるものの、三項演算子がたくさんあるコードよりは見やすいと思っています。
あくまで私の感覚ではありますが……。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?