[stitches css] 조건부 스타일링 방법

eaasurmind·2023년 1월 11일
0

TIPS

목록 보기
6/12

stitches를 5-6개월 정도 사용하면서 편했던 점이나 활용 방식에 대해 설명하고자 합니다.

stlyed-components에서의 조건부 스타일링

className driven

const Box = styled.div`
   &.selected {
    background-color: red;
   }
   `

const [toggle, setToggle] = useState(false)
...
 <Box className={toggle ? "selected" : null}>Active</Box>

props driven

const Box = styled.div(
  (props) => css`
    background: red;

    ${props.active &&
    css`
      background-color: red;
    `}
  `
);

const [toggle, setToggle] = useState(false)
...
 <Box active={toggle}>Active</Box>

stitches에서의 조건부 스타일링

variatns driven

const Box = styled('div',{
	variants: {
    active: {
      true: {
    	backgroundColor: 'red',
   	 	}
    }
}	
});

const [toggle, setToggle] = useState(false)
...
 <Box active={toggle}>Active</Box>

마찬가지로 classname 혹은 data attribute로도 핸들링이 가능하지만 variants로 핸들링하는 것이 랜더단이 가장 깔끔하고 css 작성문이 직관적이어서 좋았다.

차이점

styled components와 같은 기존 css-in-js 같은 경우 컴포넌트에서 런타임에 스타일을 수정할 때마다 스타일 태그가 더해져 dom, cssom 트리를 구축하고 css를 직렬화하여 파싱하는 시간이 필요해 연산이 무거울 수록 성능 저하를 유도할 수 있다. 데이터 시각화를 담당할 (차트, 테이블) 해당 부분에서 특히 무거움을 느꼈다.

stitches의 경우 prop에 의한 interpolation을 최소화하여 near zero run time이라 불리우는데 그 핵심이 variants에 있다. props를 받지 않는 대신 사전에 variants들을 정해 css variable로서 활용하는 방식을 통해 최적화를 이루는 방식을 택하고 있다.

profile
You only have to right once

0개의 댓글

관련 채용 정보