코딩.zip

[React CSS] 리액트에서 다양한 방법으로 CSS 적용하기 본문

프로그래밍/React

[React CSS] 리액트에서 다양한 방법으로 CSS 적용하기

김주짱 2024. 3. 19. 19:23

방법 1.  SCSS(Syntactically Awesome Style Sheets)

  • css 프리프로페서, 변수, 중첩 규칙, 믹스인, 함수 등을 지원하여 CSS 코드를 보다 효율적으로 작성

scss 라이브러리 패키지 설치 : % npm install node-sass

 

<CssModules.jsx>

import classes from "./CssModules.module.scss"

export const CssModules = () => {
    return (
        <div className={classes.container}>
            <p className={classes.title}>CSS Modules입니다.</p>
            <button className={classes.button}>버튼</button>
        </div>
    );
};

 

<CssModules.module.scss>

.container {
    border: solid 1px #aaa;
    border-radius: 20px;
    padding: 8px;
    margin: 8px;
    display: flex;
    justify-content: space-around;
    align-items: center;
}
.title {
    margin: 0;
    color: #aaa;
}
.button {
    background-color: #ddd;
    border: none;
    padding: 8px;
    border-radius: 8px;
    &:hover {
        background-color: #aaa;
        color: #fff;
        cursor: pointer;
    }
}

 

<App.js> - App을 컴포넌트로 사용

import './App.css';
import { CssModules } from './components/CssModules';

const App = () => {
  return (
    <div>
      <CssModules />
    </div>
  )
}


export default App; // export를 해줘야 index.jsx에서 App.jsx를 받을 수 있음

방법 2.  Styled JSX

  • 컴포넌트 내에 CSS를 캡슐화해 스타일링
  • 컴포넌트 단위의 스타일링을 지원하고 서버 측 렌더링과 함께 사용

styled jsx 라이브러리 패키지 설치 : % npm install styled-jsx

 

<StyledJsx.jsx>

export const StyledJsx = () => {
    return (
        <>
        <div className="container">
            <p className="title">Styled JSX입니다.</p>
            <button className="button">버튼</button>
        </div>

        {/* 전체를 백틱으로 감싸줘야함 */}
        <style Jsx>{`
        .container {
            border: solid 1px #aaa;
            border-radius: 20px;
            padding: 8px;
            margin: 8px;
            display: flex;
            justify-content: space-around;
            align-items: center;
        }
        .title {
            margin: 0;
            color: #aaa;
        }
        .button {
            background-color: #ddd;
            border: none;
            padding: 8px;
            border-radius: 8px;
        `}
        </style>
        </>
    );
};

방법 3.  Styled components

  • JavaScript 안에 CSS를 작성하는 방식

styled components 라이브러리 패키지 설치 : % npm install styled-components

 

<StyledComponents.jsx>

import styled from "styled-components";

export const StyledComponents = () => {
    return(
        <SContainer>
            <STilte>Styled components입니다.</STilte>
            <SButton>버튼</SButton>
        </SContainer>
    );
};

const SContainer = styled.div`
    border: solid 1px #aaa;
    border-radius: 20px;
    padding: 8px;
    margin: 8px;
    display: flex;
    justify-content: space-around;
    align-items: center;
`;

const STilte = styled.p`
    margin: 0;
    color: #aaa;
`;

const SButton = styled.button`
    background-color: #ddd;
    border: none;
    padding: 8px;
    border-radius: 8px;
`;

 


방법 4.  Emotion

  • 런타임에 스타일을 생성하여 빠르고 유연한 스타일링을 지원

emotion 라이브러리 패키지 설치 : % npm install @emotion/react @emotion/styled

 

emotion  사용 시 주의사항⛔️

반드시 파일 최상단에 넣어주어야 한다. 안 그럼 emotion 적용 x

/** @jsxImportSource @emotion/react */

 

<Emotion.jsx>

/* 컴포넌트 파일 안에 css 기술 하는 방법 */
/** @jsxImportSource @emotion/react */
import { jsx, css } from "@emotion/react";
import styled from "@emotion/styled";

export const Emotion = () => {
    // 1. scss 기술 방법 그대로 사용할 수 있는 기술 방법
    const containerStyle = css`
        border: solid 1px #aaa;
        border-radius: 20px;
        padding: 8px;
        margin: 8px;
        display: flex;
        justify-content: space-around;
        align-items: center;
    `;


    // 2. 인라인 스타일 기술 방법
    const titleStyle = css({
        margin: 0,
        color: "#aaa",
    })



return(
    <div css={containerStyle}>
        <p css={titleStyle}>Emotion 입니다.</p>
        <SButton>버튼</SButton>
    </div>
    );
};

    // styled-components 기술 방법
    const SButton = styled.button`
        background-color: #ddd;
        border: none;
        padding: 8px;
        border-radius: 8px;
        &:hover {
            background-color: #aaa;
            color: #fff;
            cursor: pointer;
        }
    `;

방법 5.  Tailwind CSS

  • 클래스 기반 스타일링을 통해 각 요소의 디자인을 지정

1. 필요한 라이브러리 설치

Tailwind CSS 라이브러리 패키지 설치 : % npm install -D tailwindcss@npm:@tailwindcss/postcss7-compat postcss@^7 autoprefixer@^9

 

*리액트의 경우 Tailwind 동작에 필요한 postCSS를 덮어쓸 수 없기 때문에 CRACO를 설치해서 사용 :

% npm install @craco/craco

 

2. 추가 작업

1️⃣ <package.json> 파일 수정

  "scripts": {
   /* 삭제
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
   */
   
   /* 추가 */
    "start": "craco start",
    "build": "craco build",
    "test": "craco test",
    
    "eject": "react-scripts eject"
  },

 

2️⃣ 추가 설정 필요 ➡️ <craco.config.js> 파일 추가

module.exports = {
    style: {
        postcss: {
            plugins: [
                require('tailwindcss'),

                require('autoprefixer'),
            ],
        },
    },
}

 

그 다음,

3️⃣ Tailwind CSS 프레임워크를 초기화하는 명령 : % npx tailwindcss init

➡️ Tailwind CSS를 사용하기 전에 필요한 설정 파일을 생성

 

<tailwind.config.js> 파일이 새로 생성됨

: Tailwind CSS의 다양한 옵션을 설정할 수 있다. ex) 커스텀 색상, 폰트, 여백 및 그림자 지정

module.exports = {
  purge: [],
  darkMode: false, // or 'media' or 'class'
  theme: {
    extend: {},
  },
  variants: {
    extend: {},
  },
  plugins: [],
}

 

4️⃣ purge 안에 경로 추가

purge: ['./src/**/*.{js,jsx,ts,tsx}', './public/index.html'], //purge 내용 추가

 

5️⃣ 설정파일 수정

<index.css> 파일 수정

/* 추가 */
@tailwind base;
@tailwind components;
@tailwind utilities;

/* 생략 */

 

3. Tailwind CSS 구현

<TailwindCss.jsx>

export const TailwindCss = () => {
    return(
        // class명이 필요 없는게 장점
        <div className="border border-gray-400 rounded-2xl p-2 m-2 flex justify-around items-center">
            <p className="m-0 text-gray-400">Tailwind CSS 입니다.</p>
            <button className="bg-gray-300 border-0 p-2 rounded-md hover:bg-gray-400 hover:text-white">버튼</button>
        </div>
    );
};