current position:Home>[ii) nextjs integrated styled components]

[ii) nextjs integrated styled components]

2021-08-27 05:43:36 Front end snow

Two )NextJS Integrate Styled Components

open The previous Built in NextJS project , Add the following dependencies :
npm install babel-plugin-styled-components --save-dev
npm install styled-components --save

Add the following :
1:touch .babelrc // add to babel The configuration file
The contents are as follows :

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

2: open pages/indes.js, The replacement code is as follows

import styled from 'styled-components'

const Title = styled.h1`
  font-size: 50px;
  color: ${({ theme }) => theme.colors.primary};
`

export default function Home() {
  return <Title>My page</Title>
}
 Copy code 

3:pages/_app.js, The replacement code is as follows

import { createGlobalStyle, ThemeProvider } from 'styled-components'

const GlobalStyle = createGlobalStyle`
  body {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
  }
`

const theme = {
  colors: {
    primary: '#0070f3',
  },
}

export default function App({ Component, pageProps }) {
  return (
    <>
      <GlobalStyle />
      <ThemeProvider theme={theme}>
        <Component {...pageProps} />
      </ThemeProvider>
    </>
  )
}
 Copy code 

4: pages/_document.js, The replacement code is as follows

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()
    }
  }
}
 Copy code 

copyright notice
author[Front end snow],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2021/08/20210827054335006j.html

Random recommended