개발하자

리액트를 다루는 기술-9 (컴포넌트 스타일링) 본문

Book/리액트를 다루는 기술

리액트를 다루는 기술-9 (컴포넌트 스타일링)

hyesun 2022. 11. 16. 16:31

CSS

  • 기본 스타일링 방식

1. 주의 사항

  • CSS 클래스를 중복되지 않게 만들어야 함
    • CSS Selector 이용: CSS 규칙을 적용할 요소를 의미함
      .App .logo {
      	// App 안에 있는 logo class를 탐색
      }
      
    • 네이밍 규칙 이용
 

BEM — Introduction

Introduction On smaller brochure sites, how you organize your styles isn’t usually a big concern. You get in there, write some CSS, or maybe even some SASS. You compile it all into a single stylesheet with SASS’s production settings, and then you aggre

getbem.com


Sass

  • CSS 전처리기
  • 유지보수성이 좋음
    • 코드 재활용
    • 가독성

1. .sass , .scss

  • sass는 중괄호와 세미콜론 사용하지 않음

2. utils 함수 분리

  • 여러 파일에서 사용될 수 있는 변수, 믹스인을 별도의 파일에 분리할 수 있음

3. Webpack 설정 커스터마이징

  • 세부설정 밖으로 꺼내기 (세부설정이 모두 숨겨져 있음)
yarn eject
  • sass-loader 설정을 변경하여 커스터마이징 할 수 있음

4. node_modules에서 라이브러리 불러오기

import ~library/styles
  • 물결문자(~)를 사용하면 자동으로 라이브러리 디렉터리를 탐지

CSS Module

  • css 파일을 불러와 중복없는 고유한 형태로 만들어주는 기술
    • [파일이름][클래스 이름][해시값]
  • webpack
    • v1 별도로 css-loader를 설치해줘야 사용 가능 함
    • v2 는 css 파일 명을 .module.css 로 해주면 사용 가능 함
  • scss 파일도 사용가능

1. 사용방법

  • 파일명.module.css
.wrapper {
	background-color:"red";
}
  • component.js
    • 클래스명을 프로퍼티처럼 사용 가능
import styles from "파일명.module.css"

function Component(){
	return <div className={styles.wrapper}></div>
}

2. classNames Library

  • 클래스명을 만들어주는 라이브러리
  • props에 따라서 다른 클래스명을 생성할 수 있어서 유용함
classNames('one', 'two');
classNames('one', {two:true}) one two
classNames('one', {two:false}) one

styled-components (css-in-js library)

  • 스타일을 js 파일 내에서 정의 (css-in-js)
  • 별도의 css 파일 필요 없음
  • props로 값을 전달하고 접근하기 쉬움
import styled, {css} from "styled-components"

const Box = styled.div`
	background: ${props => props.color || "blue"};
`

function Component(){
	<Box color="red" />
}

1. Tagged 템플릿 리터럴

Template literals (Template strings) - JavaScript | MDN

function tagged(...args){
	console.log(args)
}

tagged`hello ${{foo:'bar'}} ${()=>'word'}`
Comments