본문 바로가기

Web/React & Next.js

컴포넌트 스타일링

sass 스타일시트 사용하기

터미널에 명령어 npm add sass 입력

$red: #fa5252;
$orange: #fd7e14;
$yellow: #fcc419;
$green: #40c057;
$blue: #339af0;
$indigo: #5c7cfa;
$violet: #7950f2;

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

.SassComponent{
    display: flex;
    .box{
        background: red;
        cursor: pointer;
        transition: all 0.3s ease-in;
        
        &.red {
         background: $red;
         @include square(1);   
        }

        &.orange {
            background: $orange;
            @include square(2);   
        }

        &.yellow {
        background: $yellow;
        @include square(3);   
        }

        &.green {
            background: $green;
            @include square(4);   
        }

        &.blue {
            background: $blue;
            @include square(5);   
        }

        &.indigo {
            background: $indigo;
            @include square(6);   
        }

        &.violet {
            background: $violet;
            @include square(7);   
        }
        
        &.hover {
            background: black; 
        }
    }
}
import './SassComponent.scss';

const SassComponent = () =>{
    return(
        <div className='SassComponent'>
            <div className='box red'/>
            <div className='box orange'/>
            <div className='box yellow'/>
            <div className='box green'/>
            <div className='box blue'/>
            <div className='box indigo'/>
            <div className='box violet'/>
        </div>
    );
};

export default SassComponent;

sass 파일 2개로 분리하기

$red: #fa5252;
$orange: #fd7e14;
$yellow: #fcc419;
$green: #40c057;
$blue: #339af0;
$indigo: #5c7cfa;
$violet: #7950f2;

@mixin square ($size){
    $calculated: 32px * $size;
    width: $calculated;
    height: $calculated;
}
@import  './styles/utils.scss';

~

@import 구문 사용

 

sass-loader 설정 커스터마이징하기

터미널에 명령어 yarn eject 입력

오류 뜰시 yarn : 이 시스템에서 스크립트를 실행할 수 없으므로 ... 파일을 로드할 수 없습니다. 자세한 내용은 about_Execution_Policies(...) 를 참조하십시오. : 네이버 블로그 (naver.com)

 

yarn : 이 시스템에서 스크립트를 실행할 수 없으므로 ... 파일을 로드할 수 없습니다. 자세한 내용

[ 문제 상황 ] VS Code 에서 yarn eject 를 터미널 창에서 입력했는데 아래와 같은 오류 발생 [ 해결방...

blog.naver.com

참고

{
              test: sassRegex,
              exclude: sassModuleRegex,
              use: getStyleLoaders({
                  importLoaders: 3,
                  sourceMap: isEnvProduction
                    ? shouldUseSourceMap
                    : isEnvDevelopment,
                  modules: {
                    mode: 'icss',
                  },
                }).concat({
                  loader: require.resolve("sass-loader"),
                  options: {
                    sassOptions: {
                      includePaths: [paths.appSrc + "/styles"],
                    },
                  },
                }),
              // Don't consider CSS imports dead code even if the
              // containing package claims to have no side effects.
              // Remove this when webpack adds a warning or an error for this.
              // See https://github.com/webpack/webpack/issues/6571
              sideEffects: true,
            },

webpack.config.js 부분 수정

서버 재시작

@import  './styles/utils.scss'; -> @import 'tils.scss';로 수정해도 잘 작동한다

 

node_modules의 라이브러리 사용

터미널에 명령어 yarn add open-color include-media 입력

@import '~include-media/dist/include-media';
@import '~open-color/open-color'; 추가

@import  'utils.scss';
@import '~include-media/dist/include-media';
@import '~open-color/open-color';

.SassComponent{
    display: flex;
    background: $oc-gray-2;

    @include media('<768px'){
        background: $oc-gray-9;
    }

    .box{
        background: $oc-gray-2;
        cursor: pointer;
        transition: all 0.3s ease-in;
        
        &.red {
         background: $red;
         @include square(1);   
        }

        &.orange {
            background: $orange;
            @include square(2);   
        }

        &.yellow {
        background: $yellow;
        @include square(3);   
        }

        &.green {
            background: $green;
            @include square(4);   
        }

        &.blue {
            background: $blue;
            @include square(5);   
        }

        &.indigo {
            background: $indigo;
            @include square(6);   
        }

        &.violet {
            background: $violet;
            @include square(7);   
        }
        
        &.hover {
            background: black; 
        }
    }
}

화면 가로 크기가 768px이상 이면 배경이 회색이고, 768px미만이면 검정색이된다

 

css module사용

클래스는 만든 스타일을 직접 불러온 컴포넌트 내부에서만 작동한다

.wrapper{
    background: black;
    padding: 1rem;
    color: white;
    font-size: 2rem;
}

:global .something{
    font-weight: 800;
    color: aqua;
}
import styles from './CSSModule.module.css'

const CSSModule = () =>{
    return(
        <div className={styles.wrapper}>
            안녕하세요.저는<span className='something'>CSS Module!</span>
        </div>
    );
};

export default CSSModule;

웹 페이지에 전역으로 사용하는 경우 앞에 :global을 입력한다

 

className이 2개일 때 

const CSSModule = () =>{
    return(
        <div className={` ${styles.wrapper} ${styles.inverted} `}>
            안녕하세요.저는<span className='something'>CSS Module!</span>
        </div>
    );
};

위에 문법 템플릿 리터럴을 사용하였다

혹은 이렇게 쓸 수도 있다 className={[styles.wrapper, styles.inverted].join(' ')}

 

Classnames: css클래스를 조건부로 설정할 때 쓰는 라이브러리

터미널에 명령어 yarn add classnames 입력

import styles from './CSSModule.module.css'
import classnames from 'classnames'

const CSSModule = () =>{

const myclass='hello';
    console.log(classnames('one','two'));
    console.log(classnames('one',{ two:false}));
    console.log(classnames('one',myclass,{myName:true}));

    return(
        <div className={` ${styles.wrapper} ${styles.inverted} `}>
            안녕하세요.저는<span className='something'>CSS Module!</span>
        </div>
    );
};

export default CSSModule;

console에 one two, one, one hello myName라고 출력됨

 

Css-in-js라이브러리 styled-components

터미널에 명령어 yarn add styled-components 입력

import React from "react"
import styled, { css } from 'styled-components'

const Box =styled.div`
    background: ${props => props.color || 'blue'};
    padding: 1rem;
    display: flex;
`;

const Button =styled.button`
    
    background: white;
    color: black;
    border-radius: 4px;
    padding: 0.5rem;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1rem;
    font-weight: 600;

    &:hover{
        background: rgba(255, 255, 255, 0.9);
    }

    ${props => 
        props.inverted &&
        css`
        background: none;
        border: 2px soild white;
        color: white;
        
        &:hover{
            background: white;
            color: black;
        }
        `
    };

    & + button{
        margin-left: 1rem;
    }
`;

const StyledComponent = () =>{
    <Box color='black'>
        <Button>안녕하세요</Button>
        <Button inverted={true}>테두리만</Button>
    </Box>
}

export default StyledComponent;

 

'Web > React & Next.js' 카테고리의 다른 글

react 개발자 도구 크롬에 설치  (0) 2022.04.12
react 아이콘 넣기  (0) 2022.04.12
Hooks  (0) 2022.04.06
컴포넌트의 라이프사이클 메서드  (0) 2022.04.05
컴포넌트 반복  (0) 2022.04.04