프론트엔드 개발자로써 가장 중요한 역량중 하나로 재사용성이 높은 컴포넌트를 개발하는것이라고 생각합니다.
보통 버튼은 하나의 프로젝트뿐만아니라 다른프로젝트나 여기저기 많이 사용될 가능성이 높습니다.
또한 협업할때 개발생산성을 높이기위해 공통컴포넌트를 만드는것은 중요합니다.
만약 디자이너가 프로젝트 전체의 버튼을 초록색으로 바꿔주세요! 라고 했을때 공통컴포넌트를 사용하지않고 각자 만들었다면 어떨까요..?
각자 맡았던 버튼 컴포넌트를 찾아 수정을 해야할것입니다. 이는 개발생산성을 낮추게 되는것이죠. 단순 색상변경이 아니라 더 어려운 작업이라면... 아찔 그 자체일것입니다.
이제 필요한 이유는 알았으니 Button 공통 컴포넌트 디자인 시스템을 구축해보겠습니다.
재사용성 높은 Button 컴포넌트 만들어보기
import { MouseEventHandler, ReactElement } from "react";
interface ButtonType {
children: ReactElement | string;
size?: "sm" | "md" | "lg";
disabled?: boolean;
fullWidth?: boolean;
className?: string;
variant?: "primary" | "success" | "error";
onClickAction?: MouseEventHandler<HTMLButtonElement>;
}
const sizes = {
sm: "px-3 py-1.5 text-xs",
md: "px-4 py-2 text-sm",
lg: "px-5 py-4 text-lg",
};
const variantColor = {
primary: "text-white bg-blue-500 hover:bg-blue-600",
success: "text-white bg-green-600 hover:bg-green-700",
error: "text-white bg-red-600 hover:bg-red-700",
};
export default function Button({
children = "",
size = "md",
fullWidth = false,
disabled = false,
className = "",
variant = "primary",
onClickAction = () =>
console.error("무엇을 위한 버튼 인가요? 이벤트가 설정 되어있지 않습니다."),
}: ButtonType) {
const sizeClass = sizes[size];
const widthClass = fullWidth && "w-full";
const variantClass = variantColor[variant];
const disabledClass = disabled && "opacity-50 cursor-auto";
return (
<button
onClick={onClickAction}
disabled={disabled}
className={`rounded-md font-bold ${sizeClass} ${widthClass} ${className} ${variantClass} ${disabledClass}`}
>
{children}
</button>
);
}
저는 taildwind 를 사용하여 구현을 해보았습니다.
버튼이란 무언가 이벤트를 발생시키기 위한 컴포넌트이기 때문에 onClickAction 이 없을때 error 로그를 찍히게 해두었습니다.
이렇게 해준다면 만약 개발자가 실수로 아니면 까먹어서 해당기능을 구현안하였을때 디버깅이 쉬워질것입니다.
또한 위에서 정의되지않은 class들은 className 으로 전달하여 자유자재로 스타일링이 가능합니다.
구현 모습
1. 기본
// isCartEmpty 는 장바구니 상태를 관리해주는 상수입니다.
<Button size="lg" variant="primary" disabled={isCartEmpty}>
Complete purchase
</Button>
2. onClickAction 테스트
<Button
size="lg"
variant="primary"
disabled={isCartEmpty}
onClickAction={() => alert("동작 확인 테스트")}
>
Complete purchase
</Button>
위 말고도 색상변경 사이즈변경 등등 잘 작동되는것을 확인하였습니다.
다른 페이지 에서도 쉽게 사용할수있습니다!
'FrontEnd' 카테고리의 다른 글
FrontEnd - WebSocket 에 대하여 (0) | 2023.08.03 |
---|---|
FrontEnd - Tailwindcss 동적 스타일링 하기 (0) | 2023.07.27 |
FrontEnd - React-query 를 이용한 무한스크롤 구현하기 - (2) (0) | 2023.07.06 |
FrontEnd - React-query 를 이용한 무한스크롤 구현하기 - (1) (0) | 2023.07.06 |
Frontend - 프론트엔드 웹 성능 최적화 도전기 with Next.js (0) | 2023.07.03 |