Using Styled Components With Gatsby

October 10, 2020

The styles assigned with styled components are applied at javascript runtime. They generate a css stylesheets specific to your component and inject it into the head. When you use styled components for rendering things like a nav or layout, there is a strong possibility that your content will arrive on the page before the CSS required to style it, causing a usually brief but very disconcerting flash of unstyled content:

This can be solved by ensuring that Gatsby inserts your important styles inline with your html when it generates the page.

Step one: ensure that gatsby knows you are using styled components

Follow the instructions on the Gatsby styled-components page:

$ npm i gatsby-plugin-styled-components

And import the plugin to your gatsby-config:

module.exports = {
  plugins: [
    ...
    `gatsby-plugin-styled-components`
    ...
    ],
}

Step two: add important styles to a GlobalStyle component

Inside your styles folder, create a GlobalStyles.js file and add your important styles like so:

import { createGlobalStyle } from "styled-components"

const GlobalStyles = createGlobalStyle`
...
  nav.custom-nav {
    margin-bottom: 3rem;

    ul {
      margin: 0;
      padding: 0;
      text-align: center;
      list-style: none;

      display: grid;
      grid-template-columns: auto 1fr 1fr 1fr;
      grid-gap: 2rem;
      align-items: center;
    }
  }
...
`

Step three: Inline your GlobalStyles in your Layout component

Ensure that your most important styles will be inlined on every page:

...
import GlobalStyles from '../styles/GlobalStyles'

export default function Layout = () => {

  return (
    <div>
      <GlobalStyles />
      <div className="site">
        <nav className="custom-nav">
          <ul>
            ...
          </ul>
        </nav>
        ...
      </div>
    </div>
  )
}

Katie Leonard

Mostly Katie explaining things to herself.

© 2025