본문 바로가기
fastcampus

[패스트캠퍼스 수강 후기] 프론트엔드 인강 100% 환급 챌린지 35회차 미션

by 새우하이 2020. 10. 11.

CSS modules

react project에서 컴포넌트를 스타일링할 때 CSS MODULE을 사용하면 css class이름이 중복되는 것을 완벽하게 방지할 수 있다.

css파일이름을 .module.css 로 끝내면된다.

예를들어 Box.module.css 를 만들고

이를 사용할 때

import styels from "./Box.module.css" 로 불러 오게되고 고유화가 된다.

그래서

fucntion Box(){
    return <div className={styels.Box}>{styles.Box}</div>;
}

이런식으로 고유화가 되어 이름이 나타나게된다.

이럴때 유용

  • 레거시 프로젝트에 리액트르 도입 할 때
  • CSS 클래스 네이밍 규칙 만들기 귀찮을 때

우선 새로운 프로젝트를 생성해 준다.

$npx create-react-app styling-cssmodule

우선 src > components 라는 디렉터리를 생성해주고 그 아래에 CheckBox.js 라는 컴포넌트를 생성해 준다.

import React from 'react';

function CheckBox({checked, children}){
    return(
        <div>
            <label>
                <input type="checkbox" />
                <div>
                    {checked ? '체크됨': '체크 안됨'}
                </div>
            </label>
            <span>
                {children}
            </span>
        </div>
    );
}

export default CheckBox;

우선 필요한 엘리먼트들을 구현해준다.

checked 가 true이면 체크됨, 아니면 체크 안됨을 출력해주고

props로 받아온 children을 보여준다.

그리고 App컴포넌트에서 불필요한 요소들을 제거해준다.

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>
    </div>
  );
}

export default App;

useState를 사용해서 상태를 관리해줄 것이고, onChange에서 checked를 업데이트해준다.

그리고 CheckBox에 onChange와 checkBox를 넘겨준다.

그리고나서

CheckBox.js에서

import React from 'react';

function CheckBox({ checked, children, ...rest}){
    return(
        <div>
            <label>
                <input type="checkbox" checked={checked} {...rest}/>
                <div>
                    {checked ? '체크됨': '체크 안됨'}
                </div>
            </label>
            <span>
                {children}
            </span>
        </div>
    );
}

export default CheckBox;

checked와 children을 제외하고 넘어오는 것들을

...rest를 사용해서 받아와주고 input으로 넘겨준다.

렌더링 된 페이지를 보면 체크박스를 말고 체크안됨 부분을 클릭해도 값이 변하는것을 볼 수 있다. 앞으로 는 react-icons를 사용해서 아이콘으로 바꿔볼 것이다.

우선

$ npm install react-icons

로 아이콘을 설치해준다.

https://react-icons.github.io/react-icons/icons?name=md

해당 페이지에들어가보면 아이콘의 이름과 import 시키는 방법에대해서 나온다.

import React from 'react';
import { MdCheckBox,MdCheckBoxOutlineBlank } from "react-icons/md";
function CheckBox({ checked, children, ...rest}){
    return(
        <div>
            <label>
                <input type="checkbox" checked={checked} {...rest}/>
                <div>
                    {checked ? <MdCheckBox /> : <MdCheckBoxOutlineBlank />}
                </div>
            </label>
            <span>
                {children}
            </span>
        </div>
    );
}

export default CheckBox;

적용은 이런식으로 할 수 있다.

그리고 components에

CheckBox.module.css를 생성해 주고

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

.checkbox label {
  cursor: pointer;
}
.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;
}

각각의 스타일을 지정해준다.

여기서 .checkbox input의 내용은 기존의 checkbox 를 숨겨주는 것이다.

이제 해당 css를 불러와주는데

import styles from './CheckBox.module.css';

를 사용한다.

import React from 'react';
import styles from './CheckBox.module.css';
import classnames from 'classnames/bind'
import { MdCheckBox,MdCheckBoxOutlineBlank } from "react-icons/md";
function CheckBox({ checked, children, ...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;

여러개의className을 지정해줘야할 때는 템플릿 리터럴을 사용할 수 있지만.

이전에 사용했던 classnames를 설치해서

import React from 'react';
import styles from './CheckBox.module.css';
import classNames from 'classnames/bind'
import { MdCheckBox,MdCheckBoxOutlineBlank } from "react-icons/md";
const cx = classNames.bind(styles);
function CheckBox({ checked, children, ...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('checkbox', 'blabla'); 이런식으로 여러 클래스를 불러올 수 있다.

Styled component

이 라이브러리는 CSS in JS 관련 라이브러리이다.

이것은 javascript안에 css를 작성하는 것이다.

이런식으로 스타일을 자바스크립트 파일 내에서 작성할수 있다.

그리고 컴포넌트형태로 바로 사용할 수 있다.

 

Tagged Template Literal

template literal은 문자열 안에 javascript 문법을 같이 사용할 수 있는 것이다.

Tagged template literal은

text literal에서 문자와 javascript 문법이 분리되어 작동한다.

사용을 위해 yarn add styled-components

를 설치해주고,

import React from 'react';
import styled from 'styled-components'

const Circle = styled.div`
width: 5rem;
height: 5rem;
background-color:black;
border-radius:50%;
`
function App(){
    return(

        <Circle />
    );
}

export default App;

이런식으로 사용할 수 있다.

그리고

import React from 'react';
import styled from 'styled-components'

const Circle = styled.div`
width: 5rem;
height: 5rem;
background-color:${props => props.color };
border-radius:50%;
${props => props.huge &&`
width:10rem;
height:10rem;
`}
`
function App(){
    return(

        <Circle color="blue" huge/>
    );
}

export default App;

이렇게 huge값을 지정해서 크기를 키워주거나 color속성을 props로 넘겨줄 수 도있는데

huge 값 지정 부분을 보면 이렇게 해도 작동은하지만 더이상 props를 사용할 수 없게된다. 왜냐하면 저것은 그냥 taplate literal이기 때문이다.

이를 해결하기 위해서는

import React from 'react';
import styled,{css} from 'styled-components'

const Circle = styled.div`
width: 5rem;
height: 5rem;
background-color:${props => props.color };
border-radius:50%;
${props => props.huge && css`
width:10rem;
height:10rem;
`}
`
function App(){
    return(

        <Circle color="blue" huge/>
    );
}

export default App;

import 할 때 css 를 불러와주고 백틱 ` 앞에 css를 추가해준다.

vscode-styled-components를 설치하면 색상지원도 되고 자동완성도 지원해준다.

 

 

 

해당 내용은 아래 링크에서 수강할 수 있다.

프론트엔드 개발 올인원 패키지 with React Online. 👉https://bit.ly/2ETLEzm

 

프론트엔드 개발 올인원 패키지 with React Online. | 패스트캠퍼스

성인 교육 서비스 기업, 패스트캠퍼스는 개인과 조직의 실질적인 '업(業)'의 성장을 돕고자 모든 종류의 교육 콘텐츠 서비스를 제공하는 대한민국 No. 1 교육 서비스 회사입니다.

www.fastcampus.co.kr

 

댓글