클래스명 충돌 방지
📂 파일명.module.css
.wrapper {
background: black;
padding: 1rem;
}
.inverted {
background: white;
border: 1px solid black;
}
:global .something {
font-weight: 800;
}
:global: 해당 클래스가 웹페이지에서 전역적으로 사용될 때 사용한다.
📂 파일명.jsx
import styles from "./파일명.module.css";
function 파일명() {
return(
<div className={styles.wrapper}>
안녕하세요, 저는 <span className="something">hani</span>에요
</div>
)
}
className={styles.클래스명} : class 지정
className="클래스명" : 전역 class 지정
📂 global.css
공통 색상, 스타일 등은 여기에 작성하고, main이나 App 파일에 import 하면 공용으로 쓸 수 있다.
import styles from "./파일명.module.css";
function 파일명() {
return(
<div className={`${styles.wrapper} ${styles.inverted}`}>
안녕하세요, 저는 <span className="something">hani</span>에요
</div>
)
}
공식문서
CSS 클래스를 조건부로 설정할 때 유용한 라이브러리
npm install --save classnames
npm install --save @types/classnames # TS 사용 시
classNames('foo', 'bar'); // => 'foo bar'
classNames('foo', { bar: true }); // => 'foo bar'
classNames({ 'foo-bar': true }); // => 'foo-bar'
classNames({ 'foo-bar': false }); // => ''
classNames({ foo: true }, { bar: true }); // => 'foo bar'
classNames({ foo: true, bar: true }); // => 'foo bar'
// lots of arguments of various types
classNames('foo', { bar: true, duck: false }, 'baz', { quux: true }); // => 'foo bar baz quux'
// other falsy values are just ignored
classNames(null, false, 'bar', undefined, 0, { baz: null }, ''); // => 'bar'
import styles from './Button.module.css';
function Button({ primary, outline, size, disabled, loading, className }) {
return (
<button
className={`
${styles.button}
${primary ? styles.primary : ''}
${outline ? styles.outline : ''}
${styles[size] || ''}
${disabled ? styles.disabled : ''}
${loading ? styles.loading : ''}
${className || ''}
`}
disabled={disabled || loading}
>
{loading ? '로딩 중...' : '버튼'}
</button>
);
}
import cn from 'classnames';
import styles from './Button.module.css';
function Button({ primary, outline, size, disabled, loading, className }) {
return (
<button
className={cn(
styles.button,
{
[styles.primary]: primary,
[styles.outline]: outline,
[styles.disabled]: disabled,
[styles.loading]: loading
},
styles[size], // 'sm', 'md', 'lg' 등의 사이즈 클래스
className
)}
disabled={disabled || loading}
>
{loading ? '로딩 중...' : '버튼'}
</button>
);
}