0

I am using NextJS and when I use direct css import ...css alongside a styled-component createGlobalStyle. My direct css imports are always included last in my html causing some overriding issues that I've setup in GlobalStyles.

How can I resolve this?

rendered html

<head>
    <link href="/_next/static/chunks/main.js?ts=1609163560022">
    <style></style> // global styled component
    <style></style> // bootstrap imported after global styled component
</head>

_app.js

import { ThemeProvider } from "styled-components";
import 'bootstrap/dist/css/bootstrap.min.css' // this is always loaded last <head>
import GlobalStylesfrom 'styles/global'; // this is always loaded first in <head>

const theme = {
  ...
};

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

_document.js

import Document, { Html, Head, Main, NextScript } from "next/document";
import { ServerStyleSheet } from "styled-components";

export default class MyDocument extends Document {
  static getInitialProps({ renderPage }) {
    const sheet = new ServerStyleSheet();
    const page = renderPage(App => props =>
      sheet.collectStyles(<App {...props} />)
    );
    const styleTags = sheet.getStyleElement();
    return { ...page, styleTags };
  }

  render() {
    return (
      <Html>
        <Head>{this.props.styleTags}</Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }
}
3
  • 1
    I've had similar issues and ended up having a file for external css imports, local gloal css and switched positions until I ended up with what I was looking for. Very annoying indeed. Seems like you're not the only one to have this issue. There you can find my question Commented Dec 28, 2020 at 18:18
  • 1
    hey thanks very much for this! it's a bummer, I tried to copy paste the entire bootstrap.min into a styled component so I can respect the order but something in that bootstrap css is breaking styled component and nothing gets imported. I'll have to debug this more. Commented Dec 28, 2020 at 18:47
  • 1
    That's exactly what I've tried before too. I actually have the bootstrap.min.js still as a local minified stylesheet. Commented Dec 28, 2020 at 19:49

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.