[React] React Component Styling

김성현·2021년 9월 15일
0

React

목록 보기
2/2

Style Loaders

webpack에서 .js,.jsx파일은 babel-loader가 처리하고 .css파일은 style-loader,css-loader가 처리한다.

CRA(create-react-app)의 webpack 설정 확인하기

npm run eject

CRA에서 사용하는 4가지 스타일 로더

  • css
import './App.css'
  • cssModule
import styles from './App.module.css'
  • sass
import './App.scss'
import './App.sass'
  • sassModule
import styles from './App.module.scss'
import styles from './App.module.sass'

CSS, SASS

순서대로 <head>안에 <style>를 사용하여 전역으로 추가

문제점: 리액트는 컴포넌트별로 스코핑이 되지 않기 때문에 class명이 전역적으로 오염되지 않도록 관리해야한다 => CSS방법론 등장

CSS module, SASS module

[filename]_[classname]__[hash]형식으로 변경되어 <style>태그 안에 삽입됨 => class명 전역 오염문제 해결

사용

import styles from './App.module.css'

<div className={styles['App']}></div>

classnames
클래스명 관리를 편리하게 도와주는 라이브러리

npm i classnames
// truly값만 클래스 명으로 사용
classNames('foo','bar') // foo bar
classNames({foo:true},{bar:false}) // foo
classNames(null,false,'bar',undefined,0,1) // bar 1

css module과 함께 사용시에는 bind를 해주어야 한다

const cx = classNames.bind(styles)

<button className={cx('button',{loading: isLoading})} />

Styled Components

예시: styled-components, emotion
sc-hash로 구성된 새로운 class명을 생성하여 스타일을 입히는 방식

React Shadow

Shadow DOM을 사용하여 class명 전역 오염 문제 해결

Shadow DOM: HTML안에서 원본에 영향을 주지 않는 DOM 트리 복사본

설치

npm i react-shadow

사용

import root from 'react-shadow'

const styles = `
  /* css 코드 */
`

<root.div>
  // 독립적인 DOM 트리
  <style type="text/css">{styles}</style>
</root.div>

단점: 매번 styles를 지정해주고 삽입해 주어야한다.

Ant Design

만들어진 스타일된 컴포넌트를 불러와서 사용

npm i antd @ant-design/icons

index.js

import 'antd/dist/antd.css'; // or 'antd/dist/antd.less'

사용하는 css만 분할하여 가져오기
eject이후 babel-plugin-import설치

"babel": {
  "plugins":[
    [
      "imoprt",
      {
        "libraryName": "antd",
        "libraryDirectory": "es",
        "style": "css"
      }
    ]
  ]
}

Grid 레이아웃

import { Row, Col } from 'antd'

<Row gutter={[16,16]}>
  <Col span={12} offset={12} />
</Row>
  • gutter: 수평, 수직 사이 간격(px)
  • span: 24칸중 차지할 면적
  • offset: 24칸중 건너뛸 면적
profile
JS개발자

0개의 댓글