λ³Έλ¬Έ λ°”λ‘œκ°€κΈ°

μΉ΄ν…Œκ³ λ¦¬ μ—†μŒ

React κ³΅λΆ€ν•˜κΈ°(2) - CSS Module

🎢 λ²¨λ‘œνΌνŠΈμ™€ ν•¨κ»˜ν•˜λŠ” λͺ¨λ˜ λ¦¬μ•‘νŠΈ

 

ν™•μž₯자 : .module.css

클래슀 이름에 λŒ€ν•˜μ—¬ κ³ μœ ν•œ 이름듀이 λ§Œλ“€μ–΄μ§€κΈ° λ•Œλ¬Έμ—,

μ‹€μˆ˜λ‘œ CSS 클래슀 이름이 λ‹€λ₯Έ 관계 μ—†λŠ” κ³³μ—μ„œ μ‚¬μš©ν•œ CSS 클래슀 이름과 μ€‘λ³΅λ˜λŠ” 일에 λŒ€ν•˜μ—¬

κ±±μ •ν•  ν•„μš”κ°€ μ—†λ‹€.

 

<components/CheckBox.js>

* classnames μ‚¬μš© μ•ˆ ν•  μ‹œ

import React from 'react';
import { MdCheckBox, MdCheckBoxOutlineBlank } from 'react-icons/md';
import styles from './CheckBox.module.css';

function CheckBox({ children, checked, ...rest }) {
  return (
    <div className={styles.checkbox}>
      <label>
        <input type="checkbox" checked={checked} {...rest} />
        <div className={styles.icon}>
          {checked ? (
            <MdCheckBox className={styles.checked} />
          ) : (
            <MdCheckBoxOutlineBlank />
          )}
        </div>
      </label>
      <span>{children}</span>
    </div>
  );
}

export default CheckBox;

* classnames μ‚¬μš©ν•  μ‹œ

import React from 'react';
import { MdCheckBox, MdCheckBoxOutlineBlank } from 'react-icons/md';
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;

(이거 κ°€λŠ₯)

cx('one', 'two') // μ—¬λŸ¬κ°œ CSS 클래슀 적용
cx('my-component', {
  condition: true
})
cx('my-component', ['another', 'classnames'])

<components/CheckBox.module.css>

.checkbox {
  display: flex;
  align-items: center;
}

.checkbox label {
  cursor: pointer;
}

/* μ‹€μ œ input 을 숨기기 μœ„ν•œ μ½”λ“œ */
.checkbox input {
  width: 0;
  height: 0;
  position: absolute;
  opacity: 0;
}

.checkbox span {
  font-size: 1.125rem;
  font-weight: bold;
}

.icon {
  display: flex;
  align-items: center;
  /* μ•„μ΄μ½˜μ˜ ν¬κΈ°λŠ” 폰트 μ‚¬μ΄μ¦ˆλ‘œ μ‘°μ • κ°€λŠ₯ */
  font-size: 2rem;
  margin-right: 0.25rem;
  color: #adb5bd;
}

.checked {
  color: #339af0;
}

<App.js>

import React, { useState } from 'react';

import CheckBox from './components/CheckBox';

function App() {
  const [check, setCheck] = useState(false);
  const onChange = e => {
    setCheck(e.target.checked);
  };
  return (
    <div>
      <CheckBox onChange={onChange} checked={check}>
        λ‹€μŒ 약관에 λͺ¨λ‘ λ™μ˜
      </CheckBox>
      <p>
        <b>check: </b>
        {check ? 'true' : 'false'}
      </p>
    </div>
  );
}

export default App;