개발일지

[Emotion + Typescript] styled방식을 이용하여 스타일링하기 본문

개발일지

[Emotion + Typescript] styled방식을 이용하여 스타일링하기

Seobe95 2022. 10. 28. 23:20

Emotion을 사용한 이유?

평소 styled-components를 활용하여 스타일링을 진행했지만, 이번에 TS를 공부하면서 진행하는 프로젝트에서는 emotion을 이용하여 스타일링을 해보고 있다. styled-components와 emotion을 비교하는 글들이 많기는 하지만, 그런 글들과는 상관 없이 직접 사용해보면서 비교도 해보고, 차이점을 느껴보려고 한다.

 

emotion 중에서도 styled-components와 유사한 방식으로 스타일링을 할 수 있지만, 미세한 차이점이 있어 기록하기 위해 이 글을 적는다.

Emotion을 사용하면서 마주한 상황

1. props에 따라 스타일을 변경해야 하는 경우

한 컴포넌트를 스타일링 하는 경우, 부모에서 내려오는 props에 따라 스타일링을 다르게 해야하는 경우가 있다. JS의 경우, props를 무지성하게 넣어주고 처리하면 되지만, TS의 경우에는 emotion에서 사용해야 할 props들의 type을 지정해주어야 에러가 발생하지 않고 잘 작동된다.

 

...

export interface ButtonProps {
  className?: string;
  children: string;
  fullWidth: boolean;
  cyan: boolean;
}

const StyledButton = styled.button<ButtonProps>`
  border: none;
  border-radius: 4px;
  font-size: 1rem;
  font-weight: bold;
  padding: 0.25rem 1rem;
  color: white;
  outline: none;

  cursor: pointer;

  background: ${palette.gray[8]};
  &:hover {
    background: ${palette.gray[6]};
  }

  ${({ cyan }) =>
    cyan &&
    css`
      background: ${palette.cyan[5]};
      &:hover {
        background: ${palette.cyan[4]};
      }
    `}

  ${({ fullWidth }) =>
    fullWidth &&
    css`
      padding-top: 0.75rem;
      padding-bottom: 0.75rem;
      width: 100%;
      font-size: 1.125rem;
    `}
`;

const Button = ({ cyan, fullWidth, children, className }: ButtonProps) => {
  return (
    <StyledButton cyan={cyan} fullWidth={fullWidth} className={className}>
      {children}
    </StyledButton>
  );
};

export default Button;

 

2. 기존의 컴포넌트를 특정 컴포넌트에 따라서 스타일링을 다르게 해야하는 경우

emotion의 공식 문서에 따르면, 특정 컴포넌트를 다시 래핑하여 또 한 번 스타일링을 해야 하는 경우, className을 태그 내 메서드로 사용해야 한다고 한다.

 

Emotion – Styled Components

(Edit code to see changes)

emotion.sh

위에서 언급한 Button 컴포넌트를 예시를 들어 이야기하자면, className을 옵셔널 형식으로 사용하여 상위 컴포넌트에서 다시 래핑해야 하는 경우에만 className을 지정해주고, 사용하지 않는 경우에는 className을 따로 내려주지 않는 형식으로 구현했다.