[TailwindCSS] 버튼 재사용

이유정·2023년 11월 10일
0

[ArtGarden_PR]

목록 보기
12/33

버튼을 네번 써야 한다.
하나의 버튼을 만들어서 속성만 바꿔서 재사용하면 코드가 더 간결해질 것이다.
어떻게 해야 할까?
색깔은 black과 white 로 나뉘고,
크기는 3가지로 만드려고 한다.

해결

적용

이런식으로 만들어놓은 Button에다가 원하는 속성값을 넣어주면 된다.

Button.tsx

import { ReactNode } from "react";

type Color = "black" | "white";
type Size = "sm" | "md" | "lg";

interface ButtonProps {
  type?: "submit" | undefined;
  color: Color;
  size: Size;
  className?: string;
  onClick?: () => void;
  children: ReactNode;
}

function Button({
  type,
  color,
  size,
  className,
  onClick,
  children,
}: ButtonProps) {
  let combinedClassName = "";

  switch (color) {
    case "black": {
      combinedClassName =
        "text-mainyellow rounded-2xl border-2 border-mainyellow bg-mainblack ml-40";
      break;
    }
    case "white": {
      combinedClassName =
        "text-mainwhite rounded-2xl border-2 border-mainwhite bg-mainred ml-40";
      break;
    }
  }
  switch (size) {
    case "sm": {
      combinedClassName += "w-58 h-12 text-xl font-semibold px-3";
      break;
    }
    case "md": {
      combinedClassName += "w-58 h-12 text-xl font-semibold px-3";
      break;
    }
    case "lg": {
      combinedClassName += "w-58 h-12 text-xl font-semibold px-3 mr-6";
      break;
    }
  }
  return (
    <button
      type={type ? type : "button"}
      className={`${combinedClassName} ${className}`}
      onClick={onClick}
    >
      {children}
    </button>
  );
}

export default Button;

참고) https://tailwindcss.com/docs/plugins#forms
참고) https://velog.io/@wlwl99/%EB%A6%AC%ED%8C%A9%ED%86%A0%EB%A7%81-%EC%9E%AC%EC%82%AC%EC%9A%A9-%EA%B0%80%EB%8A%A5%ED%95%9C-%EB%B2%84%ED%8A%BC-%EC%BB%B4%ED%8F%AC%EB%84%8C%ED%8A%B8-%EB%A7%8C%EB%93%A4%EA%B8%B0

profile
강의 기록 블로그

0개의 댓글