React 컴포넌트 스타일링

YEZI🎐·2022년 7월 7일
0

React

목록 보기
18/46

Type 1 - JSX inline style

<!-- HTML -->
<h1 style="color: purple">헬로 월ㄹㄹ드</h1>
// JSX
<h1 style={{ color: 'purple' }}>헬로 월ㄹㄹ드</h1>

inline style을 스타일링의 주요 수단으로 사용하는 것은 권장되지 않는다.

  • JSX에선 style 어트리뷰트는 camelCase 프로퍼티를 가진 JavaScript 객체로 받아들임
    DOM 노드의 프로퍼티에 접근하는 것과 일관되게 유지하기 위해 스타일 키를 camelCase를 사용

    const divStyle = {
     color: 'blue',
     backgroundImage: 'url(' + imgUrl + ')',
    };
    
    function HelloWorldComponent() {
     return <div style={divStyle}>Hello World!</div>;
    }
  • React는 특정 숫자 인라인 스타일 프로퍼티는 “px” 접미사를 자동으로 추가

    // Result style: '10px'
    <div style={{ height: 10 }}>
     Hello World!
    </div>
    
    // Result style: '10%'
    <div style={{ height: '10%' }}>
     Hello World!
    </div>

Type 2 - JSX className

inline style을 className을 통해 style을 적용하는 것이 가장 많이 사용 되는 방식이다.

// 컴포넌트의 props나 state를 통해 class를 컨트롤
let className = 'menu';

if (this.props.isActive) {
  className += ' menu-active';
}

return <span className={className}>Menu</span>



CSS Modules

CRA(create-react-app)에서 CSS Modules을 사용할 때는 css 파일명을 [파일명].module.css 이라고 지어주어야 한다.
ex. Button.module.css

  1. Button.module.css 파일에 아래와 같은 스타일 코드가 있고

    /* Button.module.css */
    .error {
     background-color: red;
    }
  2. 다른 css 파일에도 같은 class를 쓰지만 다른 스타일이 적용된 코드가 있다.

    /* another-stylesheet.css */
    .error {
     background-color: red;
    }
  3. 위 css들을 import하여 사용할 때 같은 class를 사용하여도 Button.module.css는 styles.error로 접근을 하기 때문에 충돌이 일어나지 않는다.

    import React, { Component } from 'react';
    import styles from './Button.module.css'; // Import css modules stylesheet as styles
    import './another-stylesheet.css'; // Import regular stylesheet
    
    class Button extends Component {
     render() {
       // reference as a js object
       return <button className={styles.error}>Error Button</button>;
     }
    }

Styled Components

스타일 코드를 CSS, Sass 확장자가 아닌 Js 파일로 작성하고 작성된 Js 파일을 컴포넌트의 Js 파일과 결합하는 것(CSS in JS)이다.
React에서 포함된 기능이 아닌, 별도의 라이브러리를 사용한다.
(라이브러리 종류 및 사용량 링크)

그 중 styled components를 사용할 예정

  1. 설치

    # with npm
    npm install styled-components
    
    # with yarn
    yarn add styled-components
  2. 사용법(export)

    // Ex.style.js
    import styled from 'styled-components';
    export const Title = styled.h1`
     color : purple;
    `;
    import * as Ex from './Ex.style.js'
    return(
     <Ex.Title>
       Hello World!
     </Ex.Title>
    );

    예시 코드에서 <Title></Title><h1></h1>이 되고 Titel 변수에 들어있는 스타일 코드가 적용된다.

  3. props 사용법
    styled components는 React components는 아니다.
    하지만 React components처럼 props를 넘겨 받을 수 있다.

    return(
    	<Title color>Hello World!</Title>
    );
    
    const Title = styled.h1`
    	color : ${props => props.color ? 'purple' : 'red'};
    `;

CSS Modules vs Styled Components

Styled Components는 컴포넌트 파일과 스타일 파일을 하나로 합칠 수 있고 필요한 컴포넌트 페이지의 css 스타일 코드만을 랜더링 하기 때문에 컴포넌트 중심으로 개발하며, 개발적인 효율성에 중점을 맞춘 프로젝트에 적합하다.

css in css 방식인 CSS Modules는 모든 css 스타일 코드를 미리 랜더링 하는 것이 좋은 인터렉티브에 중심을 맞춘 프로젝트에 적합하다.

profile
까먹지마도토도토잠보🐘

0개의 댓글