FE/React

className 유틸(clsx,classnames,tailwind-merge)

yhkim_ 2025. 5. 22. 15:56

 

React에서는 HTML 태그에 class를 줄 때 다음과 같이 쓰는

<div className="text-sm text-blue-600" />

 

Tailwind나 CSS 쓸 때는 className에 여러 클래스를 써야되는데,

조건부로 특정 클래스만 적용하고 싶을 때가 많다.

 

예시로 에러가 있을 때만 빨간색으로 만들고 싶다면,

<div className={`text-sm ${hasError ? "text-red-600" : "text-gray-600"}`} />

 

이렇게 삼항연산자+ 연산자를 막 쓰게되면

  • 코드가 지저분하고 복잡해진다.
  • 중첩되면 가독성이 떨어진다.

 

그래서 등장한게 className 유틸 함수이다!

clsx, classnames 같은 애들인데

이것들은 조건에 따라 클래스를 깔끔하게 조합해주는 함수다.

 

1. clsx 

설치

npm install clsx

 

사용 예제

import { clsx } from "clsx";

const buttonClass = clsx(
  "text-sm",                         // 기본 클래스
  isActive && "bg-blue-600",         // 조건이 true면 적용됨
  isDisabled ? "opacity-50" : null   // 조건 삼항도 가능
);

return <button className={buttonClass}>버튼</button>;

 

결과

조건이 true 일때

<button className="text-sm bg-blue-600 opacity-50">버튼</button>