const myCss =css({
color:'blue',
grid:1// Error: Type 'number' is not assignable to type 'Grid | Grid[] | undefined'})
컴포넌트와 스타일을 같은 곳에 두기 (응집도)
이모션의 강력한 장점 중 하나는 스타일을 컴포넌트와 함께 둘 수 있다는 것이다. 이로 인해 컴포넌트 수정 시, 스타일 수정을 깜빡하는 실수를 줄일 수 있다.
이모션을 활용하되, 스타일은 컴포넌트와 같은 파일에 두는 습관을 들이자.
스타일 공유 방법을 고려해보기
이모션에서 스타일을 공유하는 두가지 방법이 있다.
1. 스타일 객체를 내보내기
exportconst errorCss =css({
color:'red',
fontWeight:'bold'})// Use arrays to compose stylesexportconst largeErrorCss =css([errorCss,{ fontSize:'1.5rem'}])
기본 스타일을 정해둔 뒤, 이를 활용하는 곳에서 가져와 오버라이딩을 한다.
이 방법은 단순히 “스타일”만을 공유할 때 사용하면 좋다. 다만, 이 방법은 응집도 방면에서 좋지는 못한 것을 잘 고려하자.
2. 컴포넌트 재사용하기
exportfunctionErrorMessage({ className, children }){return(<p css={{ color:'red', fontWeight:'bold'}} className={className}>{children}</p>)}// `fontSize: '1.5rem'` is passed down to the ErrorMessage component via the// className prop, so ErrorMessage must accept a className prop for this to// work!exportfunctionLargeErrorMessage({ className, children }){return(<ErrorMessage css={{ fontSize:'1.5rem'}} className={className}>{children}</ErrorMessage>)}
이 방법은 조금 더 복잡하지만, 더 강력한 방법이다. 스타일과 컴포넌트가 응집도 있게 뭉쳐있기 때문이다.
다만 코드에 적힌 대로, css 프로퍼티는 내부적으로 className 을 이용해 스타일이 적용되기 때문에, 스타일을 상속받을 컴포넌트는 className 을 구현해야 한다.
동적 스타일에는 style prop 사용하기
css 프로퍼티와 styled API는 정적 스타일에 사용되어야 한다. 동적 스타일링에는 style 프로퍼티를 사용해야 한다.
css 프로퍼티는 입력값에 따라 고유한 스타일을 만들어낸다. 예를 들어, 프사 이미지를 생각해보자. 모든 프사는 width와 height 가 40px 이며 border-radius 가 50%이다. 그런데 각 이미지는 사람마다 다를 것이다.
기본적은 동작원리는 ThemeProvider 를 앱 최상단에 배치하여 스타일을 전역적으로 공유하는 것이다.
import{ThemeProvider}from'@emotion/react'const theme ={colors:{primary:'hotpink'}}render(<ThemeProvider theme={theme}><div css={theme=>({color: theme.colors.primary})}>some other text</div></ThemeProvider>)
기본적으로 css 프로퍼티에 함수를 넣어서 theme 에 접근할 수 있고, useTheme 라는 커스텀 훅도 제공한다.
withTheme API
import*asPropTypesfrom'prop-types'import*asReactfrom'react'import{ withTheme }from'@emotion/react'classTellMeTheColorextendsReact.Component{render(){return<div>The color is {this.props.theme.color}.</div>}}TellMeTheColor.propTypes={theme:PropTypes.shape({color:PropTypes.string})}constTellMeTheColorWithTheme=withTheme(TellMeTheColor)
HOC 방식을 이용한 withTheme 를 이용해서 테마를 주입해줄 수 있다.
Labels
이모션의 기본 동작 원리가 css 프로퍼티로 받은 스타일 값을 이리저리 잘 조물조물해서 label 이라고 부르는 고유한 class name을 만들어 className 에 붙여주는 것이다.