てらブログ

てらブログ

日々の学習の備忘録

Tailwind CSSのコーディングルールを考える

目的

ルールを決めることで、自由度の高いTailwind CSSをちゃんと管理していきたい。

結論

Tailwindについては、まだこれだ!という運用方法が分かっていないので、継続的にアンテナを張って良い方法を検討していきたい。

なるべくコンポーネント分割し、JSXの可読性を上げる

下記コードだとパッと見て分かりにくい。

const Index = () => {
  return (
    <div className="flex items-center justify-center h-screen bg-gray-100">
      <div className="w-[400px] h-[300px] flex flex-col justify-center px-4 mx-auto bg-white rounded-lg shadow-md dark:bg-gray-800">
        <h1 className="mb-4 text-xl font-semibold text-gray-700 dark:text-gray-200">
          Tailwind好きです
        </h1>
        <p className="mb-4 text-gray-600 dark:text-gray-400">好きな理由は……</p>
        <button className="px-4 py-2 text-sm font-medium text-white bg-blue-600 rounded-lg hover:bg-blue-500">
          こちらをクリック!
        </button>
      </div>
    </div>
  );
};

export default Index;

例えば下記のように各々をコンポーネント化すれば、JSX箇所は可読性が上がる。
ただし何でもかんでもコンポーネント化すると、意味的におかしな箇所が出てきそうだし、収拾がつかずそもそもやりたかった整理ができなくなる。
重複箇所や、コンポーネントとして外だしするべき箇所でコンポーネント化するべき。

const Card = ({ children }) => (
  <div className="w-[400px] h-[300px] flex flex-col justify-center px-4 mx-auto bg-white rounded-lg shadow-md dark:bg-gray-800">
    {children}
  </div>
);

const Title = ({ children }) => (
  <h1 className="mb-4 text-xl font-semibold text-gray-700 dark:text-gray-200">
    {children}
  </h1>
);

const Text = ({ children }) => (
  <p
    className="mb-4 text-gray-600 dark:text-gray-400"
  >
    {children}
  </p>
);

const Button = ({ children }) => (
  <button
    className="px-4 py-2 text-sm font-medium text-white bg-blue-600 rounded-lg hover:bg-blue-500"
  >
    {children}
  </button>
);

const Index = () => {
  return (
    <div className="flex items-center justify-center h-screen bg-gray-100">
      <Card>
        <Title>Welcome to Tailwind CSS!</Title>
        <Text>Lorem ipsum dolor sit amet...</Text>
        <Button>Click me</Button>
      </Card>
    </div>
  );
};

テンプレートリテラルで改行する

下記のようにユーティリティが長くなった場合は

<DialogTrigger className="flex h-8 w-40 items-center justify-start rounded-lg px-2 font-bold  text-gray-800 hover:bg-blue-100 focus-visible:outline-blue-300 active:bg-blue-200">

下記のように改行したい。
これもなんでもかんでも改行するのは違うと思うが、2・3つくらいで改行を挟んであげると可読性は良くなりそう。

<DialogTrigger
    className="
      flex h-8 w-40 
      items-center justify-start 
      rounded-lg px-2 font-bold  text-gray-800 
      hover:bg-blue-100 
      focus-visible:outline-blue-300 
      active:bg-blue-200
    "
>

tailwind-mergeを使用する

こちらは以前学んだ通り。