module.css
import styles from './Button.**module.css**'
const Button = props => <button className={**styles['button']**} />
export default Button
- 일반 css 파일과 달리 module.css에 정의된 스타일 클래스들은 컴포넌트에서 실제로 쓰일 때, 고유한 값을 가지는 클래스 이름으로 변경된다. ⇒ css 속성이 겹치지 않게 된다.
- className=’button’ (css 방식) ⇒ className={styles[’button’]} (module.css 방식)
classNames
classNames('foo', 'bar')
classNames({foo: true}, {bar: false}) // foo 만 나옴
classNames(styles['button'], styles['loading'])
// classNames와 styles 결합하기
const cx = **classNames.bind(styles)**
cx('button', 'loading') // classNames(styles['button'], styles['loading']) 와 같음
- classNames : 클래스 이름 두 개 이상을 간편하게 쓸 수 있다.
- classNames.bind(styles) : classNames와 styles를 동시에 쓰게 되면 코드가 길어지는 문제점을 해결하기 위해서 classNames와 styles를 결합하여 코드를 짧게 만들 수 있다.
styled-components
import styled, { css } from 'styled-components'
const StyledButton = **styled**.button` // 백틱 기호 써야함
background: transparent;
border-radius: 3px;
border: 2px solid royalblue;
${props => props.primary && // 물려 받는 속성이 있는 경우
css`
background: royalblue;
color: white;
:hover {
border 2px solid red;
}
`}
export StyledButton
- css 파일을 따로 만들지 않고, 컴포넌트 내부에서 직접 컴포넌트에 스타일을 주는 방식
- 컴포넌트가 부모로부터 물려 받은 속성(props)가 있다면 ${} 내부에서 화살표 함수를 통해서 물려 받은 속성과 styled 속성을 동시에 적용시킬 수 있다.
GlobalStyle
import { createGlobalStyle } from 'styled-components'
const GlobalStyle = createGlobalStyle`
button {
color: yellow;
}
`
function App() {
return (
<GlobalStyle />
)
}
- 모든 컴포넌트에 적용되는 스타일
- 최상위 요소에서 렌더링되어야 한다.