Button UI
Button은 variant가 많고, Tailwind CSS는 nested selector를 지양함.
그러므로 다음과 같이 React component로 구현한다.
설치
$ pnpm add tailwind-merge clsx class-variance-authority
3가지를 설치해주고, 가이드 2-3을 참조하여 src/lib/utils.ts를 입력한다.
Button library 예시
src/components/ui/button.tsx
import { VariantProps, cva } from 'class-variance-authority';
import { ComponentProps } from 'react';
import { cn } from '@/lib/utils';
const buttonVariants = cva(
'inline-flex items-center justify-center rounded-md text-sm font-medium transition-colors focus:outline-none focus:ring-2 focus:ring-slate-400 focus:ring-offset-2 disabled:opacity-50 disabled:pointer-events-none data-[state=open]:bg-slate-100',
{
variants: {
bgcolor: {
default: 'bg-slate-900 text-slate-50 hover:bg-slate-700',
pink: 'bg-pink-900 text-pink-50 hover:bg-pink-500',
},
outline: {
default: 'border border-transparent',
black: 'border-4 border-black',
},
size: {
default: 'h-10 py-2 px-4 text-sm',
sm: 'h-9 px-2 rounded-md text-xs',
lg: 'h-11 px-8 rounded-md text-base',
},
},
defaultVariants: {
bgcolor: 'default',
outline: 'default',
size: 'default',
},
}
);
interface ButtonProps
extends ComponentProps<'button'>,
VariantProps<typeof buttonVariants> {}
const Button = ({
className,
bgcolor,
outline,
size,
...props
}: ButtonProps) => {
return (
<button
className={cn(
buttonVariants({
bgcolor,
outline,
size,
className,
})
)}
{...props}
/>
);
};
export default Button;
Component에서 Button 사용 예시
page.tsx
import Button from '@/components/ui/button';
const ButtonPage = () => {
return (
<>
<Button>My Button 1</Button>
<Button bgcolor="pink">My Button 2</Button>
<Button bgcolor="pink" outline="black">
My Button 3
</Button>
<Button bgcolor="pink" outline="black" size="lg">
My Button 4
</Button>
</>
);
};
export default ButtonPage;
'Next.js 개발 가이드 > 03. 퍼블 가이드' 카테고리의 다른 글
2. checkbox (1) | 2023.12.17 |
---|---|
1. local font (0) | 2023.12.14 |