Web/React

Next.js 고정 스타일링, styled-components 설치 및 사용법

__bo0o_ 2022. 2. 5. 04:05

1. CSS-in-JS

간단하게 말하자면 Javascript 코드에서 CSS를 작성하는 방식

 

2. CSS-in-JS 라이브러리 중, styled-components 설치

npm i styled-components

- emotion 등등..

 

2-1) styled-components용 babel 플러그인 및 preset 설치

npm i --save-dev babel-plugin-styled-components
npm i babel-preset-next

2-2) 프로젝트 루트 폴더 바로 밑에 .babelrc 파일 생성하여 플러그인 활성화

{
  "presets": ["next/babel"],
  "plugins": [["styled-components", { "ssr": true }]]
}

https://github.com/nblthree/nextjs-with-material-ui-and-styled-components/blob/master/.babelrc

2-3) pages 폴더 밑에 _document.js 파일 생성

import Document from 'next/document'
import { ServerStyleSheet } from 'styled-components'

export default class MyDocument extends Document {
    static async getInitialProps(ctx) {

    const sheet = new ServerStyleSheet()
    const originalRenderPage = ctx.renderPage

    try {
      ctx.renderPage = () =>
        originalRenderPage({
          enhanceApp: (App) => (props) =>
            sheet.collectStyles(<App {...props} />),
        })

      const initialProps = await Document.getInitialProps(ctx)
      return {
        ...initialProps,
        styles: (
          <>
            {initialProps.styles}
            {sheet.getStyleElement()}
          </>
        ),
      }
    } finally {
      sheet.seal()
    }
  }
}

https://github.com/nblthree/nextjs-with-material-ui-and-styled-components/blob/master/pages/_document.js

 

3. 고정 스타일링 사용법

고정 스타일링 기본 사용법은 아래와 같다.

import React from "react";
import styled from "styled-components";

const StyledButton = styled.button`
  background-color: pink;
  border: none;
  color: white;
  padding: 13px 23px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  margin: 4px 2px;
  cursor: pointer;
`;

function Button() {
	return <StyleButton>버튼</StyleButton>;
}

1) material-ui 같은 ui component framework를 추가적으로 넣어 사용할 수도 있고

// components/base/Button/styles.tsx
import styled from "styled-components";
import { Container, Box, Select, Button } from '@material-ui/core';

export const StyledButton = styled(Button)`
	height: 4rem;
`;

...

2) export 한 위 스타일 변수 자체를 컴포넌트처럼 재사용할 수도 있다

// .../example.tsx
import { StyledButton } from 'components/base/Button/styles';

const Example = () => {
	return (
    	<StyledButton>버튼</StyledButton>
    );
};

 

4. 가변 스타일링

또한 파라미터 값에 따라서

가변적으로 스타일링을 할 수 있는데

ex) button color같은

그 부분은 아래 사이트를 참고하자!

https://www.daleseo.com/react-styled-components/

 

 

ps. styled-jsx와 styled-components 중첩하여 사용할 수 없다.

styled-jsx을 사용할 때 render 방식과 styled-components의 Nesting(중첩) 기능은 지원하지 않는다는 단점이 있다.

같이 사용하면 개발자 도구 콘솔창에

Warning: Prop `className` did not match.

위와 같은 오류가 뜨기 때문에 둘 중 한 가지만 사용하길 바란다.

 

https://styled-components.com/docs/basics

https://soft91.tistory.com/91

https://stackoverflow.com/questions/51791163/warning-prop-classname-did-not-match-when-using-styled-components-with-seman

https://ahnanne.tistory.com/38

반응형

'Web > React' 카테고리의 다른 글

Nextjs Prism Syntax highlighting  (0) 2022.03.23
Next.js 절대경로 설정  (0) 2022.02.25
Next.js styled-jsx 사용법  (0) 2022.01.28
eject  (0) 2021.11.23
scss 설치 및 사용법  (0) 2021.11.23