들어가며

모던 웹 개발에서 조건부 스타일링은 필수적인 요소이다. 특히 Tailwind CSS를 사용할 때, 여러 조건에 따라 다른 스타일을 적용해야 하는 경우가 많다. 경험상 프론트에서 조건에 따라 스타일링 하는 경우가 많았다. clsx 라이브러리를 사용하여 이를 효율적으로 관리하는 방법을 알아보자.

clsx란?

clsx는 조건부 클래스명 관리를 위한 유틸리티 라이브러리다. 특히 Tailwind CSS와 함께 사용할 때 그 진가를 발휘한다.

설치 방법

# npm 사용
npm install clsx

# pnpm 사용 (Next.js 15 권장)
pnpm add clsx

# yarn 사용
yarn add clsx

기본 사용법

1. 단순 조건부 스타일링

import clsx from 'clsx';

function Button({ variant = 'primary', disabled }) {
  return (
    <button
      className={clsx(
        'px-4 py-2 rounded-md',
        {
          'bg-blue-500 hover:bg-blue-600': variant === 'primary',
          'bg-gray-500 hover:bg-gray-600': variant === 'secondary',
          'opacity-50 cursor-not-allowed': disabled
        }
      )}
    >
      Click me
    </button>
  );
}

2. 다중 조건 처리

import clsx from 'clsx';

function Alert({ type = 'info', message }) {
  return (
    <div
      className={clsx(
        'p-4 rounded-lg',
        {
          'bg-blue-100 text-blue-800': type === 'info',
          'bg-green-100 text-green-800': type === 'success',
          'bg-red-100 text-red-800': type === 'error',
          'bg-yellow-100 text-yellow-800': type === 'warning'
        }
      )}
    >
      {message}
    </div>
  );
}

clsx vs 템플릿 리터럴

템플릿 리터럴 방식

function Card({ isActive }) {
  return (
    <div className={`
      p-4 rounded-lg shadow-md
      ${isActive ? 'bg-blue-500 text-white' : 'bg-white text-gray-800'}
    `}>
      Card Content
    </div>
  );
}

clsx 방식

import clsx from 'clsx';

function Card({ isActive }) {
  return (
    <div
      className={clsx(
        'p-4 rounded-lg shadow-md',
        {
          'bg-blue-500 text-white': isActive,
          'bg-white text-gray-800': !isActive
        }
      )}
    >
      Card Content
    </div>
  );
}

고급 사용법

1. 공통 스타일 분리

const baseStyles = 'p-4 rounded-lg shadow-md';
const variantStyles = {
  primary: 'bg-blue-500 text-white',
  secondary: 'bg-gray-500 text-white',
  outline: 'border-2 border-blue-500 text-blue-500'
};

function Button({ variant = 'primary', className }) {
  return (
    <button
      className={clsx(
        baseStyles,
        variantStyles[variant],
        className // 외부에서 추가 스타일 적용 가능
      )}
    >
      Button
    </button>
  );
}

2. 동적 스타일 계산