CSS Module
- 클래스명을 고유(유일)하게 함.
- 파일 경로, 파일 이름, 클래스 이름, 해쉬값 등이 클래스 이름에 이용됨.
- CSS 클래스 중첩 방지.
- 컴포넌트 별로 스타일 적용시 유용하게 이용 가능.
- CRA(Create-react-app)로 만든 프로젝트에서 CSS 확장자를
.module.css
로 지정하면 쉽게 이용 가능. (라이브러리 별도 설지 X)
- 클래스명은
styles
객체로 제공됨.
- 따라서, 참조시
{styles.클래스명}
을 이용.
import React from "react";
import styles from "./Box.module.css";
function Box() {
return <div className={styles.Box}>{styles.Box}</div>;
}
export default Box;
.Box {
background: black;
color: white;
padding: 2rem;
}
classnames
활용
bind
기능을 활용하면 좀더 수월함.
classNames
을 classnames/bind
에서 불러오면 사용 가능.
classNames.bind(styles)
를 변수에 할당 후 이용하면,
변수('one')
처럼 styles
객체 표현을 생략 가능.
import React from 'react';
import styles from './CheckBox.module.css';
import classNames from 'classnames/bind';
const cx = classNames.bind(styles);
function CheckBox({ children, checked, ...rest }) {
return (
<div className={cx('checkbox')}>
<label>
<input type="checkbox" checked={checked} {...rest} />
<div className={cx('icon')}>
{checked ? (
<MdCheckBox className={cx('checked')} />
) : (
<MdCheckBoxOutlineBlank />
)}
</div>
</label>
<span>{children}</span>
</div>
);
}
export default CheckBox;
- 또한 복수의 클래스 지정 시
변수('one', 'two')
로 표현.
cx('one', 'two')
cx('my-component', {
condition: true
})
cx('my-component', ['another', 'classnames'])
Sass에서 사용은?
- Sass에서도 사용 가능.
- 확장자를
.module.scss
로 설정하면 됨.