Tailwind 조건 Util 함수 작성하기

1 minute read
2024-07-26

빈번하게 사용되는 조건에 따른 className

conditional className props
<div
  className={
    cn([
      activeTab === tab.id 
        ? '' 
        : 'hover:text-slate-500/60',
      // ...
    ])
  }
>
  {/* */}
</div>


별로 없을 때는 상관없지만, 하나씩 늘어나면 코드가 점점 길어지고 가독성이 떨어지게 된다. 이를 위해 유틸함수로 개선할 수 있다.


conditional style 유틸함수

src/lib/utils.ts
/**
 * 참/거짓에 따른 className 을 쉽게 적용하기 위한 util function
 */
export function cs(
  condition: boolean,
  trulyClassValue: ClassValue,
  falsyClassValue: ClassValue = ''
) {
  return condition ? trulyClassValue : falsyClassValue;
}


거짓인 경우 생략 가능하도록 빈 문자열을 기본값으로 세팅해주었다.


component
import { cs } from '@/lib/utils'
 
<div
  className={
    cn([
      cs(activeTab !== tab.id, 'hover:text-slate-500/60'),
      cs(activeTab === tab.id, 'text-red-300')
      // ...
    ])
  }
>
  {/* */}
</div>


이렇게 유틸함수를 이용하면 클래스가 늘어나도 가독성이 유지가 되는 이점이 있다.