Skip to Content
FrontendTailwindCSS02-classNames

1. classNames

1.1 설치

shellscript
1
yarn add classnames

1.2 간단한 사용법

tsx
1
import classNames from 'classnames'
2
3
classNames('one', 'two') // = ‘one two‘
4
classNames('one', { two: true }) // = ‘one two‘
5
classNames('one', { two: false }) // = ‘one‘
6
classNames('one', ['two', 'three']) // = ‘one two three‘
7
8
const myClass = 'hello'
9
classNames('one', myClass, { myCondition: true }) // = ‘one hello myCondition'

이런 식으로 여러 가지 종류의 파라미터를 조합해 CSS 클래스를 설정할 수 있기 때문에, 컴포넌트에서 조건부로 클래스를 설정할 때 매우 유용하다.

tsx
1
/**
2
* highlighted 값이 true면, highlighted 클래스가 적용
3
* theme으로 전달받는 문자열은 내용 그대로 클래스에 적용
4
*/
5
const MyComponent = ({ highlighted, theme }) => (
6
<div className={classNames('MyComponent', { highlighted }, theme)}>Hello</div>
7
)

props 값에 따라 다른 스타일을 주기가 쉽다.

반대로 위 코드를 classnames를 쓰지 않고 적용해보면 다음과 같다.

tsx
1
const MyComponent = ({ highlighted, theme }) => (
2
<div className={`MyComponent ${theme} ${highlighted ? 'highlighted' : ''}`}>Hello</div>
3
)