8-3. 컴포넌트 스타일링 - CSS Module(2)

송한솔·2023년 4월 30일
0

ReactStudy

목록 보기
44/54

클래스 이름 두개 이상 적용하기

CSS Module을 사용하여 클래스 이름을 두 개 이상 적용할 때는 다음과 같이 코드를 작성합니다.

/* CSSModule.module.css */

/* 자동으로 고유해질 것이므로 흔히 사용되는 단어를 클래스 이름으로 마음대로 사용 가능 */
.wrapper {
    background-color: black;
    padding: 1rem;
    color: white;
    font-size: 2rem;
}

.inverted {
 color: black;
 background-color: #fff;
 border: 1px solid #000;
}
/* 글로벌 CSS를 작성하고 싶다면? */
:global .something {
    font-weight: 800;
    color: aqua;
}
// CSSModule.js

import styles from "./CSSModule.module.css";

const CSSModule = () => {
    console.log(styles);
    return (
        <div className={`${styles.wrapper} ${styles.inverted}`}>
            안녕하세요, 저는 <span className="something">CSS Module!</span>
        </div>

    );
};

export default CSSModule;

템플릿 리터럴(Template Literal)

<div className={`${styles.wrapper} ${styles.inverted}`}>

위 코드에서 보면 ES6문법인 템플릿 리터럴(Template Literal)을 사용하여 문자열을 합해 주었습니다.
이 문법을 사용하면 문자열 안에 자바스크립트 레퍼런스를 쉽게 넣어 줄 수 있습니다.

const name = "리액트";
// const message = "제 이름은" + name + "입니다.";
const message = `제 이름은 ${name}입니다.

여기서 사용되는 ` 문자는 백틱이라고 부르며, 키보드에서 Esc아래에 있는 키입니다.

템플릿 리터럴 문법을 사용하고 싶지 않다면 다음과 같이 작성할 수 있습니다.

<div className={[styles.wrapper, styles.inverted].join('')}>

0개의 댓글