본문 바로가기
SPA/Next

[Next] Styled Components 사용하기

by J4J 2022. 1. 11.
300x250
반응형

안녕하세요. J4J입니다.

 

이번 포스팅은 Styled Components 사용하는 방법에 대해 적어보는 시간을 가져보려고 합니다.

 

 

 

Styled Components 사용 방법

 

[ 1. 패키지 설치 ]

 

$ npm install styled-components
$ npm install -D babel-plugin-styled-components

// typescript 사용할 경우 추가
$ npm install -D @types/styled-components

 

 

반응형

 

 

[ 2. babel 설정 ]

 

root경로에 .babelrc 파일을 생성하여 다음과 같은 설정을 해주시면 됩니다.

 

{
    "presets": ["next/babel"],
    "plugins": [
        [
            "babel-plugin-styled-components",
            { "fileName": true, "displayName": true, "pure": true }
        ]
    ]
  }

 

 

 

한 가지 알고 가셔야 될 점은 React에서 Styled Copmonents를 사용하기 위해 설정을 할 때는 babel 설정을 따로 해주지 않습니다.

 

하지만 Next에서 babel 설정을 해주는 이유는 Styled Components로 설정한 스타일들이 적용되기 전에 렌더링이 완료되기 때문입니다.

 

결국, babel 설정을 해주지 않는다면 작성된 코드들에 맞게 스타일이 적용되지 않는 상황들이 발생하게 될 것이고 이를 방지하기 위해 babel 설정을 해줘야 합니다.

 

 

 

테스트

 

설정이 제대로 되었는지 간단히 테스트를 하기 위해 index.tsx 파일에 다음과 같이 코드를 작성해보겠습니다.

 

import * as React from 'react';
import { NextPage } from 'next';

import styled from 'styled-components';

const Index: NextPage = () => {
    return (
        <Wrapper>
            <InputText />

            <RedButton>Red</RedButton>
            <BlueButton>Blue</BlueButton>
        </Wrapper>
    );
};

export default Index;

// div styled
const Wrapper = styled.div`
    width: 840px;

    margin: 0 auto;

    display: flex;
`

// input에 속성값을 추가한 styled
const InputText = styled.input.attrs({
    type: 'text'
})`
    width: 100%;

    margin: 0 24px;

    display: block;
`

// button styled
const Button = styled.button`
    width: 120px;
    height: 50px;

    border: none;
    border-radius: 6px;

    color: #fff;

    margin: 0 8px;

    cursor: pointer;
`

// Button styled를 이용한 styled
const RedButton = styled(Button)`
    background-color: red;
`

// Button styled를 이용한 styled
const BlueButton = styled(Button)`
    background-color: blue;
`

 

 

728x90

 

 

코드를 작성하고 실행해보면 다음과 같이 스타일이 정상적으로 적용된 것을 확인할 수 있습니다.

 

실행 결과

 

 

 

 

 

 

 

이상으로 Styled Components 사용하는 방법에 대해 간단하게 알아보는 시간이었습니다.

 

읽어주셔서 감사합니다.

 

 

 

728x90
반응형

댓글