프로젝트 진행중 tailwind css 의 공통적인 부분이 계속 생기는 것을 보고 다른 사람들은 어떻게 재사용성을 증가시키는지 찾아보다가 tools 가 있어 짚어보았다.
npm install clsx
import clsx from 'clsx'
function Button({isPrimary, isLarge, isDisabled, className1}) {
return (
<button
className = {clsx(
'px-4 py-2 rounded',
{
'bg-blue-500 text-white:': isPrimary,
'bg-gray-300 text-gray-700': !isPrimary,
'text-lg': isLarge,
'opacity-50 cursor-not-allowed': isDisabled
},
className1
)}
>
Click me
</button>
)
}
<Button className="mt-4 uppercase"> Click me </Button>
tailwind css 를 작성해놓고 prop으로 받아온 변수들에게 조건부로 적용을 하게끔 사용할 수 있다.
즉 여러 className 을 조건부를 통해 하나의 문자열로 만들어주는 라이브러리이다.
npm install class-variance-authority
import {cva} from 'class-variance-authority'
const button1 = cva{
'py-4 px-2 rounded',
{
varients: {
intent: {
parimary: 'bg-blue-500 text-white',
secondary: 'bg-gray-200 text-gray-800',
},
size: {
small: 'text-sm',
large: 'text-lg',
},
defaultVariants: {
intent: 'primary',
size: 'small'
},
}
}
}
function Button({intent, size, className }) {
return (
<button className= {button1({intent, size, className})}>
Click me
</button>
)
}
button1
변수를 선언하여 cva 메서드를 사용하여 기본적인 tailwind css 적용하고 prop으로 받아오는 상태에 따라 css를 적용할 수 있다.
defaultVariants에 intent와 size를 적용 시켜놓아서 만약 button1()
로 호출하게 된다면 primary와 small 이 적용이되어 표현된다.
Tailwind 클래스 간의 충돌을 해결하는데 유용한 라이브러리
npm install tailwind-merge
import {twMerge} from 'tailwind-merge'
function Button({className1}) {
return (
<button className = {twMerge(
'py-4 px-2 bg-blue-500 text-white rounded',
className1
)}
>
Click me
</button>
)
}
<Button className = 'bg-red-500 py-3'/>
// 결과 px-4 py-3 bg-red-500 text-white rounded 적용
여러 className 을 하나의 문자열로 만들어주는 도구인데 clsx와 용도가 조금 다르다
우선 순위가 py-4
px-2
가 있어 py-3
은 적용이 안 되는게 정상이지만 twMerge
를 사용하여 py-3
가 적용이 된다.
따라서 clsx
와 twMerge
를 결합시켜 cn
이라는 유틸함수를 만들 수 있다.
실무에서는 tailwind-merge와 clsx 를 사용 해서 유틸함수를 만들어서 더욱 쉽게 사용할 수 있다.
import {twMerge} from 'tailwind-merge'
import {clsx, type ClassValue} from 'clsx'
export function cn(...inputs:ClassValue[]) {
return twMerge(clsx(inputs))
}
import {cva} from 'class-variance-authority'
import cn from 'util/cn.tsx'
const buttonVariant = cva(
'py-4 py-2 rounded',
{
variants:{
variants: {
primary: 'bg-blue-500 text-white',
second: 'bg-gray-200 text-gray-800',
},
size: {
small:'text-sm',
large: 'text-lg'
},
}
defaultVariants: {
varaints: 'primary',
size: 'large'
}
}
)
function Button({variants, size, className, ...props}){
return (
<butoon className= {cn({buttonVariant({variants:second,size}),className)}
{...props}
)
}
cn 함수안에 cva 기능을 사용한 것으로 좀더 간략하고 재사용성이 높게 사용할 수 있다.