Ricardo de Paula
Ricardo de Paula

Reputation: 632

Styled Components Global style duplicated in Next

Why is my global styles duplicated? I'm using Styled Components and I created a file GlobalStyles.js. in the root of the aplication, like i do in React or Gatsby. In this file I call the Hook createGlobalStyle and define all global css. The problem is that all my global css is duplicated in Next.

enter image description here

_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()
    }
  }
}

_app.js

import { GlobalStyles } from '../../GlobalStyles'
import Layout from '../components/Layout'

function MyApp({ Component, pageProps }) {
  return (
    <>
      <Layout>
        <GlobalStyles />
        <Component {...pageProps} />
      </Layout>
    </>
  )
}

export default MyApp

I am absolutely new in Next - is my first App.

"dependencies": {
    "babel-plugin-styled-components": "^1.13.2",
    "next": "11.1.0",
    "react": "17.0.2",
    "react-dom": "17.0.2",
    "styled-components": "^5.3.1"
  },

It should probably be something very simple.

.babelrc

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

Upvotes: 1

Views: 1257

Answers (1)

sasa
sasa

Reputation: 459

Try adding global styles to the collect styles sheet, and remove it from _app.js file. You'll end up with something like this:

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

Let me know if it works...

Upvotes: 3

Related Questions