React) 컴포넌트 스타일링

iamokian·2022년 3월 26일
0

React

목록 보기
10/10

9. 컴포넌트 스타일링

리액트에서 컴포넌트를 스타일링할 때는 다양한 방식을 사용할 수 있다. 정해진 방식은 없지만 프로젝트마다 요구하는 스펙이 다르고, 취향이 다르기 때문에 취향에 맞게 사용하면 된다.


1. 일반 CSS

소규모 프로젝트를 개발하고 있다면 스타일링 시스템을 적용하는것이 번거로울수 있다. 그런 상황에는 프로젝트에 이미 적용되어 있는 기본 CSS시스템을 사용하는 것 만으로도 충분하다.

.App {
	text-align: center;
}

.App .logo {
	animation: App-logo-spin infinite 20s linear;
    height: 40vmin;
}

.App header {
	background-color: #282c34;
    min-height: 100vh;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    font-size: calc(10px + 2vmin);
    color: #fff;
}

...
import './App.css';

...

App.js에 App.css파일을 import시켜서 스타일링을 해준 모습이다. CSS를 안다면 기본적으로 이해할 수 있는 형태이다.


2. Sass

Sass는 css전처리기로 복잡한 작업을 쉬게 할 수 있도록 해준다. 스타일 코드의 재활용성을 높여주고 코드의 가독성을 높여준다. 기본적으로 Sass나 Scss를 사용해봤다면 css와 마찬가지로 이해하기 쉽다. 하지만 sass 라이브러리를 설치해주어야 한다. 그래야 sass를 css로 변환해준다.

//SassComponent.scss

$red: #fa5252;
$orange: #fd7e14;
$yellow: #fcc419;
$green: #40c057;

@mixin square($size) {
	$calculated: 32px * $size;
    width: $calculated;
    height: $calculated;
}

.SassComponent {
	display: flex;
    .box {
    	background: #FF0000;
        cursor: pointer;
        &.red {
        	background: $red
            @include square(1);
        }
        &.orange {
        	background: $red
            @include square(1);
        }
        &.yellow {
        	background: $red
            @include square(1);
        }
        &.green {
        	background: $red
            @include square(1);
        }
    }
}
//SassComponent.js

import './SassComponent.scss';

...

스타일링을 적용시킬 컴포넌트에 scss 파일을 import시켜서 적용시킨다. 그리고 공통으로 사용되는 변수와 믹스인이 있다면 이를 분리해서 사용할 수도 있다.


3. styled-components

'CSS-in-JS' 라이브러리중 하나인 styled-components이다. 이를 대체할 수 있는 라이브러리로는 emotion도 있다. 라이브러리 이므로 시작전에 설치를 해주어야 한다. styled-components를 사용하면 자바스크립트 파일 하나에 스타일 까지 작성할 수 있는 장점이있다.

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

const Box = styled.div`
	//pops로 넣어 준 값을 직접 전달해 줄 수 있다. 설정한 props값이 없으면 blue로 설정한다.
	background: ${props => props.color || 'blue'};
	padding: 1rem;
	display: flex;
`;

const Button = styled.button`
	background: #fff;
	color: #000;
	border-radius: 4px;
	padding: 0.5rem;
	display: flex;
	align-items: center;
	justify-content: center;
	box-sizing: border-box;
	font-size: 1rem;
	font-weight: 600;
	
	/* &문자를 사용해 sass처럼 자기 자신 선택 가능 */
	&:hover {
		background: rgba(255, 255, 255, 0.9);
	}
	
	/* inverted값이 true일 때 특정 스타일 부여해주는 코드 */
	${props =>
		props.inverted &&
      	css`
          background: none;
          border: 2px solid #fff;
          color: #fff;
          &.hover {
          background: #fff;
          color: #000;
          }
	`};
`;

const StyledComponent = () => (
	<Box color="black">
  		<Button>안녕하세요</Button>
  		<Button inverted={true}>안녕하세요</Button>
  	</Box>
)

일반 classNames를 사용하는 css/sass를 비교했을 때, 가장 큰 장점은 props 값으로 전달해 주는 값을 쉽게 스타일에 적용할 수 있다는 것이다. 그리고 스타일 작성이 쓰여진 ` 은 Tagged 템플릿 리터럴 이라고 부른다. 템플릿 안에 자바스크립트 캑체나 함수를 전달할 때 온전히 추출할 수 있다는 것이다.

간추려 보자면 styled.태그명을 사용해 구현한다.

import styled from 'styled-components';

const MyComponent = styled.div`
	font-size: 2rem;
`;

font-size 2rem스타일이 적용된 div로 만들어진 리액트 컴포넌트가 생성된 것이다. 이것을 나중에

<MyComponent>react</MyComponent>

와 같은 형태로 사용할 수 있다. 만약 div가 아닌 태그를 스타일링 하고싶다면 styled.태그명 같은 형태로 뒤에 태그명을 넣어주면 된다.


리액트를 다루는 기술을 읽고 요약한 글 입니다😊

profile
필기하고 기록하고

0개의 댓글