(styled-components) css helper

SuKyoung·2023년 1월 7일
13

TIL

목록 보기
1/3
post-thumbnail

코드리뷰 중에 단순 css 변경만 하는 경우에는 css helper를 쓰지 않는게 좋다는 피드백을 받았습니다. styled-components에 대해 좀 더 찾아보고 제가 이해한 것을 바탕으로 기록을 남깁니다. 이 글에 잘못된 정보가 있거나 추가로 보완해주시고 싶은 내용이 있다면 언제든 댓글로 피드백 부탁드리겠습니다.

CSS helper란

css helper에 대한 설명은 styled-components 공식문서에 아래와 같이 기술되어 있습니다.

📖 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.

(번역) css helper 함수는 css template literal 내부에 interpolations을 포함하고 있는 형태를 생성합니다. 따라서 interpolation 내부에 함수를 가진 template literal 형태를 반환하는 경우에 css helper를 사용하세요. 이는 Vanilla JavaScript에서도 작동되는 것과 동일한 방식입니다.

const complexMixin = css`
  color: ${props => (props.whiteColor ? 'white' : 'black')};
`
  • css <== 이 부분이 generate CSS
  • ‘color: ${props => (props.whiteColor ? 'white' : 'black')};’ <== from a template literal with interpolations

Vanilla JavaScript에서 interpolation이 어떻게 사용되는지는 mdn의 Tagged templates에서 확인할 수 있습니다.

+) 위의 설명과 더불어, styled-components 공식문서의 tagged template literals를 읽어보니, css helper는 tagged templates을 사용하여 구현되어 있을 것으로 추측됩니다. (언젠가 코드 까보고 확인하는 걸로...)


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

(번역) 단순 string을 interpolating하는 경우에는 css helper를 사용할 필요없고, 함수를 interpolating 하는 경우에만 쓰세요.

// ❌ bad way
const styledComponent = styled.div`
	${props => props.hasColor && css`
		color: red;
    `}
`;
// ⭕ good way
const styledComponent = styled.div`
	${props => props.hasColor && ` // ✅ 단순 string이므로 template literal로 충분
		color: red;
    `}
`;



📖 Returns an array of interpolations, which is a flattened data structure that you can pass as an interpolation itself.
If you leave off the css your function will be toString()ed and you'll not get the results you expected.

(번역) interpolation을 사용하여 css 함수를 만들었다면, 해당 함수 자체를 다른 interpolation 내부에서 사용할 수 있습니다.

import styled, { css } from 'styled-components'

const complexMixin = css`
  color: ${props => (props.whiteColor ? 'white' : 'black')};
`

const StyledComp = styled.div`
  /* This is an example of a nested interpolation */
  ${props => (props.complex ? complexMixin : 'color: blue;')};
`

만약 위의 코드에서, complexMixin에 css helper를 사용하지 않았다면, complexMixin 내부의 color: ${props => (props.whiteColor ? 'white' : 'black')}; 이 부분이 통째로 문자열로 StyledComp에 전달되기 때문에 원하는 결과가 나오지 않습니다.

Usage

1️⃣ (단순 스트링이 아니라) 함수를 사용하여 css값을 리턴하는 경우

const Title = styled.h1`
  /* Text centering won't break if props.upsidedown is falsy */
  ${props => props.upsidedown && 'transform: rotate(180deg);'}
  text-align: center;
`;

💡 Tips: && operator를 사용하면 truthy일때만 실행됩니다.

🔎 참고: styled-components doc Tagged Template Literals
styled-components ignores interpolations that evaluate to undefined, null, false, or an empty string (""), which means you're free to use short-circuit evaluation to conditionally add CSS rules.


2️⃣ 여러개의 css 속성을 동시에 변경하는 경우

const sizeStyles = css`
  ${props =>
    props.size === 'large' &&
    css`
      height: 3rem;
      font-size: 1.25rem;
    `}

  ${props =>
    props.size === 'medium' &&
    css`
      height: 2.25rem;
      font-size: 1rem;
    `}

    ${props =>
      props.size === 'small' &&
      css`
        height: 1.75rem;
        font-size: 0.875rem;
      `}
`;

💡 Tips: styled-components 내부에서 switch-case, if문, for문, console.log 전부 사용가능합니다.
(위 예문코드 같은 경우에는 switch-case나 if문을 사용할 수 있을 듯)


REFERENCE

profile
👩‍💻 Frontend Engineer | 📝 Hobby Blogger

1개의 댓글

comment-user-thumbnail
2023년 1월 7일

오호 css``는 잘 안써봤는데 아예 css자체를 리턴할때 꽤 쓰나보군요.. 화긴

답글 달기