# nextjsのプロジェクトでclass-variance-authorityを採用した

Table of Contents

レビューは勉強になる

最近案件が立て込んでいるのは6月のまとめに書いたんだけど、結果いくつかのプロジェクトで実装ではなく、ただのレビューアーと化している。

実装がしたいって今まで強く思っていた。

実装が実力を伸ばす唯一の手段だと思っていたけど、レビューも真剣にやればすごい勉強になることに気が付いた。

というのもレビューするには、まずコードをしっかり読まなければならないし、知らないプラグインとの出会いがあり、それを調べることで相当勉強になる。

で、今回出会ったのが、class-variance-authorityというプラグイン。

class-variance-authorityとは??

簡単に言うとvariantsを定義して条件分岐をわかりやすくするもの。

公式にあるbuttonコンポーネントの例がわかりやすい。

import React from "react";
import { cva, type VariantProps } from "class-variance-authority";
const button = cva("button", {
variants: {
intent: {
primary: [
"bg-blue-500",
"text-white",
"border-transparent",
"hover:bg-blue-600",
],
secondary: [
"bg-white",
"text-gray-800",
"border-gray-400",
"hover:bg-gray-100",
],
},
size: {
small: ["text-sm", "py-1", "px-2"],
medium: ["text-base", "py-2", "px-4"],
},
},
compoundVariants: [{ intent: "primary", size: "medium", class: "uppercase" }],
defaultVariants: {
intent: "primary",
size: "medium",
},
});
export interface ButtonProps
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
VariantProps<typeof button> {}
export const Button: React.FC<ButtonProps> = ({
className,
intent,
size,
...props
}) => <button className={button({ intent, size, className })} {...props} />;

https://github.com/joe-bell/cva/blob/main/examples/react-with-tailwindcss/src/components/button/button.tsx

今まで自分が実装したときはjsxのほうに条件をいろいろ書いてコードが読みにくくなっていたけど、これならコードが整理されてわかりやすい。

懸念点があった

懸念点はprettierが効くのか、そしてvscodeの拡張機能が正常に動くかという点だった。

でもそれも公式でしっかり解消されていた。

prettier

tailwindのフォーマットが行われるようprettier-plugin-tailwindcssというプラグインを入れている。

prettier-plugin-tailwindcss

で、これがvariantsに書くと効かないことが分かった。

https://github.com/tailwindlabs/tailwindcss/discussions/7558#discussioncomment-7345390

ここで議論されており、解決されていた。

この通り行った結果、うまく動いた。

Tailwind CSS IntelliSense

これは自動でtailwindの補完、つまり予測を出してくれるvscodeの拡張機能。

これを効くようにするには、

{
"tailwindCSS.experimental.classRegex": [
["cva\\(([^)]*)\\)", "[\"'`]([^\"'`]*).*?[\"'`]"],
["cx\\(([^)]*)\\)", "(?:'|\"|`)([^']*)(?:'|\"|`)"]
]
}

という風に設定すればいい。で、再起動をする。


うん、勉強になった。

My avatar

Thanks for reading my blog post! Feel free to check out my other posts or contact me via the social links in the footer.


More Posts

Comments