intent, size, variant prop값들에 따라 버튼의 스타일을 다르게 하고 싶은 경우 다음과 같은 방법으로 코드를 작성할 수 있다.
여기서 cva를 이용하면 가독성 좋고 재사용성이 높은 컴포넌트를 만들 수 있다.
$ npm i class-variance-authority
cva 함수에 스타일을 작성해준다
cva('기본 스타일',
{
variants: {
prop1: {
속성1: css
속성2: css
},
prop2: {
속성1: css
속성2: css
}
}, compoundVariants: [
{
prop1: 속성1,
prop2: 속성2,
className: css
}
],
defaultVariants: {
prop1: 기본 prop1 속성,
prop2: 기본 prop2 속성,
prop3: 기본 prop3 속성,
},
})
import { VariantProps, cva } from "class-variance-authority";
import { ComponentProps, PropsWithChildren } from "react";
const buttonVariant = cva(
"rounded text-[15px] font-semibold border transition hover:brightness-90 active:brightness-75",
{
variants: {
intent: {
primary: "border-sky-500",
secondary: "border-slate-500",
},
size: {
sm: "px-3 py-1 text-[13px]",
md: "px-4 py-1.5 text-[15px]",
},
variant: {
outline: "bg-white",
contained: "text-white",
},
},
compoundVariants: [
{
intent: "primary",
variant: "contained",
className: "bg-sky-500",
},
{
intent: "primary",
variant: "outline",
className: "text-sky-500",
},
{
intent: "secondary",
variant: "contained",
className: "bg-slate-500",
},
{
intent: "secondary",
variant: "outline",
className: "text-slate-500",
},
],
defaultVariants: {
intent: "primary",
size: "md",
variant: "contained",
},
}
);
type ButtonVariant = VariantProps<typeof buttonVariant>;
type ButtonProps = {} & ButtonVariant & ComponentProps<"button">;
function Button({
intent,
size,
variant,
children,
...props
}: PropsWithChildren<ButtonProps>) {
return (
<button className={buttonVariant({ intent, size, variant })} {...props}>
{children}
</button>
);
}
export default Button;
실무에서 유용하게 사용될 것 같은 내용이라서 좋았습니다 ^0^
많이 써보고 익숙해지자~