TIL 50 | Styled Component Helper - css

이사감·2021년 5월 25일
0

CSS

목록 보기
13/13
post-thumbnail

Styled Component Helper - css

Styled Component 에는 여러 Helper가 있는데, 그중에서 css에 대해 간단히 알아보는 글.

참고 - Styled Component Helpers

  • createGlobalStyle
  • keyframes
  • css
  • StyleSheetManager
  • isStyledComponent
  • withTheme
  • ThemeConsumer

스타일 컴포넌트를 어떻게 사람들이 쓰고 있는지 찾아볼 때 가장 많이 봤던 것이 css helper였다.

사용할 때에는 다음과 같이 import를 먼저 한다.

import { css } from 'styled-components'

스니펫으로는 imsccss을 입력하면 됨. 짱 편함 👍🏻

언제 쓰지?

공식문서에서는 다음과 같이 소개하고 있다.

A helper function to generate CSS from a template literal with interpolations. You need to use this if you return a template literal with functions inside an interpolation due to how tagged template literals work in JavaScript.

If you're interpolating a string you do not need to use this, only if you're interpolating a function.

즉 일반적인 템플릿 리터럴로 사용가능한 상황에서는 쓰지 않아도 되지만 스타일 안에서 함수를 사용할 때에는 css helper를 사용해야한다.

오늘 다음과 같은 스타일 컴포넌트를 작성하며 css를 빼먹었더니 에러가 났다. props를 가지고 조건부 스타일링(?)을 하는데 이때 스타일 안에서 함수를 사용했기 때문에 css helper를 사용해야 함~

const NavBtn = styled.button`
  background-color: ${props =>
    props.selected
      ? css`
          ${({ theme }) => theme.colors.bgGray}
        `
      : 'white'};
  border: ${props =>
    props.selected
      ? css`
          1px solid ${({ theme }) => theme.colors.border}
        `
      : 'none'};
`;

그런데 이렇게 쓰면 너무 못생겼으니까 구조분해 할당으로 다음과 같이 리팩토링할 수 있다고 종택님이 알려주셨다.

  background-color: ${({ theme, selected }) =>
    selected ? theme.colors.bgGray : 'white'};
  border: ${({ theme, selected }) =>
    selected ? `1px solid ${theme.colors.border}` : 'none'};
profile
https://emewjin.github.io

0개의 댓글