Button에 Compound pattern 적용하기

sumi-0011·2023년 5월 21일
0

LandingButton에 Compound pattern을 적용하여
<LandingButton.Dark />와 같은 형태로 접근 가능하게 하였습니다.

처음에는 style 분리를 위해서 Chakra UI를 참고하여forwardRef를 사용한 방법을 사용해봤지만, ref가 없다는? 오류가 발생하면서 이유를 알수가 없어서
forwardRef를 제거한 코드로 작성해보았습니다.

장점

이와 같은 방식으로 사용한다면,
자주 접근해야 하는 코드들을 props가 아닌 방식을 사용하면서
좀 더 어떤 버튼인지 명시적으로 나타내기에 좋다고 생각했습니다.

해당 코드

import type { ComponentPropsWithoutRef } from 'react';
import styled from 'styled-components';

type ButtonColorSchemaType = 'dark' | 'primary';
type ButtonSizeSchemaType = 'xs' | 'sm' | 'md' | 'lg';

const colorSchemas = {
  dark: {
    backgroundColor: '#202020',
    color: '#fff',
  },
...
};

const sizes = {
  xs: {
    height: '25px',
  },
...
};

interface ButtonStyledProps {
  colorSchema?: ButtonColorSchemaType;
  size?: ButtonSizeSchemaType;

  minW?: string;
}

interface ButtonProps
  extends ComponentPropsWithoutRef<'button'>,
    ButtonStyledProps {}

function LandingButton({ children, ...props }: ButtonProps) {
  return <LandingButtonWrapper {...props}>{children}</LandingButtonWrapper>;
}

const LandingButtonWrapper = styled.button<ButtonStyledProps>`
  ...

  ${({ colorSchema }) => colorSchemas[colorSchema || 'primary']}
  ${({ size }) => sizes[size || 'md']}
  ${({ minW }) => minW && `min-width: ${minW}px;`}
`;

const Dark = (props: ButtonProps) => (
  <LandingButton {...props} colorSchema="dark" />
);

const Primary = (props: ButtonProps) => (
  <LandingButton {...props} colorSchema="primary" />
);

export default Object.assign(LandingButton, { Dark, Primary });

사용 방법


<LandingButton.Dark />
<LandingButton.Primary />
profile
안녕하세요 😚

0개의 댓글