토이 프로젝트/Emotion core

[1차시] 버튼 컴포넌트 만들기

콩쥐땃쥐 2025. 1. 14. 20:56

버튼 컴포넌트는 버튼을 만들 때 속성들을 매번 입력하기 귀찮고 코드가 길어져서 재사용을 하기 위해 만든 것이다.

1차적으로

[리팩토링] 재사용 가능한 버튼 컴포넌트 만들기

이 블로그의 글을 참고해서 버튼 컴포넌트를 제작하였다.

코드

더보기
import React from 'react';
import { cva, VariantProps } from 'class-variance-authority';
import { ReactNode } from 'react';

type Color = 'blue' | 'white' | 'gray';
type Size = 'sm' | 'md' | 'lg';

interface ButtonProps {
  type?: 'submit' | undefined; // type이 undefined인 경우에는 'button'으로 지정
  color: Color;
  size: Size;
  className?: string; // 추가로 적용하고 싶은 className이 있을 경우 사용
  onClick?: () => void;
  children: ReactNode;
}

const Buttons = ({ type, color, size, className, onClick, children }: ButtonProps) => {
  let combinedClassName = ''; //className 중첩

  switch (color) {
    case 'blue': {
      combinedClassName =
        '';
    }
    case 'white': {
      combinedClassName =
        '';
    }
    case 'gray': {
      combinedClassName = 'rounded-2xl bg-[#F5F5F5]';
    }
  }

  switch (size) {
    case 'sm': {
      combinedClassName += 'py-1.5 px-3 text-sm focus:ring-4';
      break;
    }
    case 'md': {
      combinedClassName += 'py-2 px-4 text-sm focus:ring-2';
      break;
    }
    case 'lg': {
      combinedClassName += ' px-[206px] py-[23px] text-[14px]';
      break;
    }
  }

  return (
    <button type={type ? type : 'button'} className={`${combinedClassName} ${className}`} onClick={onClick}>
      {children}
    </button>
  );
};

export default Buttons;

스타일링을 하다 이상한 것 같아서 갈아엎는 도중에 회의에 들어갔고 두 분 다 cva를 사용하고 계셔서 코드를 통일하기 위해 나도 cva를 사용하기로 했다(다시 다 갈아엎어야하는...)

cva

cva? 처음 들었을 때는 이게 뭔가 하고 검색해봤다.

cva란? (class-variance-authority)

전통적인 CSS 접근 방식으로는 스타일 출력을 완전히 제어하기 어렵기 때문에, 보다 간편한 방법으로 UI를 정의할 수 있게 도와주는 라이브러리이다.

 

(cva정리하는 글,,, 버튼 컴포넌트 만든 코드,,,)

 

참고 링크

테일윈드를 통한 컴포넌트 스타일링 방법 (Tailwind + CVA + tailwind-merge)

cva로 재사용 가능한 UI 만들기 (feat. cva: class-variance-authority, tailwind-merge, clsx, shadcn)

CVA, 재사용 컴포넌트를 만들 수 있는

class-variance-authority (cva) 사용법 간단 정리 (제일 도움됨)