Nextjs styled-components
본문 바로가기

Frontend/React

Nextjs styled-components

그냥 리액트 nextjs와 타입스크립트용 nextjs는 약간다르다.

 

그냥 리액트 nextjs

yarn add styled-components

_document.js

import React from "react";
import Document, { Html, Head, Main, NextScript } from "next/document";
import { ServerStyleSheet } from "styled-components";
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();
    }
  }

  render() {
    return (
      <Html>
        <Head />
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }
}

export default MyDocument;

.babelrc

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

예시

import styled from 'styled-components';

let StyledButton = styled.button`
  background : ${ props => props.bg };
  color : black;
  padding : 10px;
`;

function Detail(){
  return (
    <div>
        <StyledButton bg="orange">Orange</StyledButton>
        <StyledButton bg="blue">Blue</StyledButton>
    </div>
  )
}

 

타입스크립트 Nextjs

다음에 정리

 

https://styled-components.com/docs/advanced#nextjs

 

styled-components: Advanced Usage

Theming, refs, Security, Existing CSS, Tagged Template Literals, Server-Side Rendering and Style Objects

styled-components.com

 

반응형