[React/Emotion] 함수형으로도 사용 가능한 스타일링

Jinjer·2021년 11월 13일
0
post-thumbnail

1. 프롤로그

Styled-Component나 meterial-UI, Ant-deign 등
React 애플리케이션 개발을 더 빠르고 쉽게 만들어주는 컴포넌트 라이브러리가 존재한다

이번 시간엔 Emotion으로 스타일링을 적용해보자
기본적인 환경 설정을 위해 프로젝트를 하나 만들고 터미널을 열어 아래의 명령어를 입력해준다

npm install react @emotion/css @emotion/react @emotion/styled
or
yarn add react @emotion/css @emotion/react @emotion/styled

@emotion/css 공식 문서에서 자세한 내용을 참고할 수 있다

2. @emotion/css

기본적인 사용 예시를 한번 보자면
className이 중복없이 자동으로 부여 되는 특징을 가지고 있고
객체 안에서 템플릿 리터럴을 이용할 수 도 있다

import { css } from "@emotion/css"
import { COLOR } from "../constants/color"

const Layout = ({ children }) => {
    const point = css`
        color: ${COLOR.POINT};
    `;
    
    const base = css`
        color: ${COLOR.WHITE};
    `;
    
    return (
        <div className={css`
          display: flex;
          background: ${COLOR.GREY}
        `}>
            <div className="container">
                <div css={ { base, point } }>포인트 컬러가 기본 컬러를 덮어 쓰게 됩니다.</div>
                <div css={ { base } }>{children}</div>
            </div>
        </div>
    );
};

‘base’와 같이 컴포지션 타입으로 만들어 두면 위와 같이 재사용이 가능하다

3. @emotion/react

React에서 사용하기 편하도록 만들어진 라이브러리이다
css prop을 지원하는 것이 특징

import { css } from "@emotion/react";

const Layout = ({ children }) => {
    return (
        <div css={wrap} className="wrap">
            <div className="container">
                <div className="inner">{children}</div>
            </div>
        </div>
    );
};

// Default
const wrap = css`
  display: flex;

  .container {
    background: #5e5e5e;
  }
`;

// Functional
const wrap = () => {
  return css`
  display: flex;

  .container {
    background: #5e5e5e;
  }
`};

인라인으로 선언하는 것을 지양한다면 문자열이나 함수형으로도 선언할 수 있다!

4. @emotion/styled

스타일이 적용된 컴포넌트를 가져다가 사용하는 방식
Styled-components이나 Ant Design과 매우 유사한 것을 알 수 있다

import styled from "@emotion/styled";

const Layout = ({ children }) => {
    const Inner = styled.div({
        background: '#5e5e5e';
    });

    const Container = styled.div({
        [Inner]: {
            background: '#f4f4f4';
        }
    })
    
    return (
        <div className="wrap">
            <Container>
                <Inner>{children}</Inner>
            </Container>
        </div>
    );
};

부모 컴포넌트에서 자식 컴포넌트를 선택하여 스타일을 재정의할 수 있다!

5. React Version.17 Issue

React가 최근 v.17로 변경되면서 runtime 엔진이 emotion과 충돌되는 이슈가 있다고 한다

아래와 같이 구문을 추가해주면 문제없이 해결된다!!
(CodeSandBox 이용 시에도 동일하게 추가해야 동작한다)

/** @jsxImportSource @emotion/react */
import { css } from "@emotion/react";

6. 정리

✔ Styled-Component와 사용법이 매우 유사하다
✔ 다른 라이브러리에 비해 용량이 비교적 가볍다
✔ 그러면서도 다양한 옵션을 지원한다(with 타입스크립트)
✔ 안 쓸 이유가 없다👏

profile
프론트엔드개발자

0개의 댓글