[Storybook] emotion + typescript로 버튼 컴포넌트 만들기

김효선·2021년 12월 19일
1

스토리북으로 가장 먼저 만들어보았던 컴포넌트는 버튼 컴포넌트!
버튼이라고 만만하게 보면 안된다.
disabled, fullWidth, hover...등 경우의 수가 많기 때문에 작성해야하는 스타일이 많다 :)

버튼 컴포넌트 작성

디자인

피그마로 직접 만들어본 버튼 디자인이다.
피그마 처음 써봤는데 기존에 포토샵, 일러스트만 쓰던 사람으로써..
바리에이션 기능이나 오토 레이아웃 등 너무 좋은 기능이 많아서 대박 이라는 감탄을 외치며 만졌던 기억이 난다.

버튼 사이즈는 height를 기준으로 삼는다.

코드 작성

import { ButtonHTMLAttributes, forwardRef } from 'react';
import styled from '@emotion/styled';

export interface IButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
  variant?: 'default';
  size?: 'xs' | 'sm' | 'md' | 'lg' | 'xl';
  color?: 'blue' | 'black';
  label?: string;
  fullWidth?: boolean;
}

const Button = forwardRef<HTMLButtonElement, IButtonProps>((props, ref) => {
  const {
    variant = 'default',
    size = 'md',
    color = 'blue',
    label,
    disabled,
    fullWidth,
    ...restProps
  } = props;
  return (
    <ButtonElement
      variant={variant}
      size={size}
      color={color}
      ref={ref}
      {...restProps}
    >
      {label}
    </ButtonElement>
  );
});


const ButtonElement = styled.button<IButtonProps>`
  ${(props) =>
    props.size === 'md' &&
    `
      height: 36px;
      padding: 0 14px;
      font-size: 1.4rem;
      border-radius: 6px;
    `};

  ${(props) =>
    props.variant === 'default' &&
    props.color === 'blue' &&
    !props.disabled &&
    `
      color: #fff;
      background-color: #478dff;
      &:hover {
        background: #2B7CFE;
      }
      &:active {
        background: #1B64DA;
      }
    `};

  font-weight: 500;
  transition: 100ms ease-out;
`;
export default Button;

ref를 전달 받는 상황을 위해 forwardRef로 감싸준다.
디자인에 맞게 사이즈, 컬러 등 interface로 타입을 정의한다.
interface에 없는 disabled를 props에서 꺼낼 수 있는 이유는 ButtonHTMLAttributes<HTMLButtonElement> 을 확장했기 때문이다.

md 사이즈의 blue 색상 버튼을 만들어보았다.
이 상태에서 yarn storybook을 터미널에 입력하면,

yarn storybook

성공적으로 버튼이 나온다 :)

size, color, fullWidth, disabled 등등 디자인 가이드에 맞게 추가하면 버튼 컴포넌트 작성 끝 !!

profile
차근차근 나아가는 주니어 프론트엔드 개발자

0개의 댓글