question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Classes and styles not aplied after Gatsby Build

See original GitHub issue

I have been experiencing some unexpected behavior when trying to use styled-components in a Gatsby build that only seems to happen in production builds. I have a hook that changes the value of props being passed to a styled component. When the page is loaded in the browser it appears as though the styles are correct in react dev tools but the DOM does not reflect these changes.

It works as intended with npm start, but not with npm build Example CodeSandbox: https://codesandbox.io/s/styled-components-issue-2629-js89j Example Repo: https://github.com/BraveLilToaster/styled-components-issue-2629

Environment

System:

  • OS: Linux 4.15 Ubuntu 18.04.1 LTS (Bionic Beaver)
  • CPU: (8) x64 Intel® Core™ i7-8550U CPU @ 1.80GHz
  • Memory: 5.31 GB / 15.12 GB
  • Container: Yes
  • Shell: 5.4.2 - /usr/bin/zsh

Binaries:

  • Node: 10.16.0 - ~/.nvm/versions/node/v10.16.0/bin/node
  • Yarn: 1.12.1 - /usr/bin/yarn
  • npm: 6.9.0 - ~/.nvm/versions/node/v10.16.0/bin/npm

npmPackages:

  • babel-plugin-styled-components: ^1.10.1 => 1.10.1
  • styled-components: ^4.3.1 => 4.3.1

Reproduction

  1. Create new Gatsby project from the default-starter
  2. npm install --save gatsby-plugin-styled-components styled-components babel-plugin-styled-components
  3. Add a styled component that takes a prop like color.
  4. Add a hook to set the color based on screen size.

Steps to reproduce

  1. Run npm run build
  2. Run npm run serve

Expected Behavior

Screen size is detected to be over 900px wide. Value of props passed down to the styled components change. Classes/styles update in the DOM. image

Actual Behavior

Screen size is detected to be over 900px wide. Value of props passed down to the styled components. Classes/styles update in react dev tools, but the DOM maintains the same classes/styles from the initial load. image

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Reactions:2
  • Comments:24 (6 by maintainers)

github_iconTop GitHub Comments

9reactions
decepuliscommented, Jan 27, 2020

I think I’m still encountering this as of v5. (if I understand the issue correctly 😳Gatsby, styled components, and hydration are pretty new turf for me)

My Gatsby site provides an item from localStorage to the styled-components ThemeProvider.

In dev mode, this is fine. The site loads in whatever mode was stored in localStorage. In production mode, however, upon loading the mode from localStorage, my GlobalStyle responds to the theme, whereas my styled components do not.

Setting the theme through user interaction gets things going again. Setting the state with a useEffect() hook instead of with an initial value to useState also works; this is my current workaround, though it flashes a bit.

I tried to make a demo of this, both in a repo, and below in the Reproduction section.

Happy to answer questions or provide details!

Environment

package.json

  "dependencies": {
    "babel-plugin-styled-components": "^1.10.7",
    "gatsby": "^2.19.7",
    "gatsby-plugin-styled-components": "^3.1.18",
    "react": "^16.12.0",
    "react-dom": "^16.12.0",
    "styled-components": "^5.0.0"
  },

gatsby-config.js

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

Reproduction

src/pages/index.js

import React, { useState, useEffect } from "react"
import styled, { createGlobalStyle, ThemeProvider } from "styled-components"

// GlobalStyle should set the body background to red
// unless the theme is localstorage; then the background is green
const GlobalStyle = createGlobalStyle`
  body {
    color: white;
    background-color: red;
    ${props =>
      props.theme.mode === "localstorage" && "background-color: green;"}
  }
`

// StyledP should set its background to blue
// unless the theme is localstorage; then the background is green
const StyledP = styled.p`
  background-color: blue;
  ${props => props.theme.mode === "localstorage" && "background-color: green;"}
`

export default () => {
  // We load the state from localstorage,
  // defaulting to 'default' if localstorage is unavailable or unset.
  // This means that the ssr site will always be rendered as 'default'
  const [theme, setTheme] = useState(
    typeof window !== "undefined"
      ? localStorage.getItem("storageTheme") ?? "default"
      : "default"
  )

  // commenting out the initial value lines inside useState()
  // and enabling these lines fixes the problem
  // useEffect(() => {
  //   setTheme(
  //     typeof window !== "undefined"
  //       ? localStorage.getItem("storageTheme") ?? "default"
  //       : "default"
  //   )
  // }, [setTheme])

  const changeTheme = event => {
    localStorage.setItem("storageTheme", event.target.value)
    setTheme(event.target.value)
  }
  return (
    <ThemeProvider theme={{ mode: theme }}>
      <GlobalStyle />

      <h1> The theme is {theme} </h1>

      <p>
        GlobalStyle turns the body red when 'default', green when 'localstorage'
      </p>
      <StyledP>
        StyledP turns this blue when 'default', green when 'localstorage'
      </StyledP>

      <select value={theme} onChange={changeTheme}>
        <option value="default">Default</option>
        <option value="localstorage">LocalStorage</option>
      </select>
    </ThemeProvider>
  )
}

Screenshots

Only in production, when localstorage is stored in localStorage, the whole site is supposed to turn green. However, only the GlobalStyle responds: styles applying globally, but not locally

Toggling the theme back and forth, or setting it with useEffect instead of an initial value provided to useState, seems to fix the issue but things are okay after setting the state through interaction after first render

4reactions
FrancisCalizocommented, May 5, 2020

@decepulis Thank you for the example repo! This was (I guess still is) driving me crazy.

I have nearly identical code to yours and exact same issues: My theme styles are loaded perfectly from localStorage in development mode. But when it comes to production, only some styles load and some do not (seems to be all the child components that do not load the theme styles). But if I were to change the theme through user interaction, voila! Everything works perfectly.

I currently am using your “useEffect” temporary solution. I suppose the “flash” is better than the mess of colors of multiple themes. I suppose we’re still not at a resolution to this issue?

Read more comments on GitHub >

github_iconTop Results From Across the Web

CSS Class not working after importing in gatsby - Stack Overflow
The problem is naming the CSS file in gatsby. change the file name from products_module.css to products.module.css .
Read more >
Enhancing Styles with CSS-in-JS | Gatsby
Keep in mind that styles aren't applied until the JavaScript loads hence a plugin to extract the styles is necessary to prevent flash...
Read more >
Styling Gatsby Site with CSS - Ibaslogic
In this folder, create a file called style.css and add the following base styles: ... Save your files and see your styles applied...
Read more >
How To Use Static Files in Gatsby | DigitalOcean
Tutorial Series: How To Create Static Web Sites with Gatsby.js ... Since the CSS file is meant to be applied to the entire...
Read more >
Gatsby Tutorial #6 - Styling Components - YouTube
Hey gang, in this Gatsby tutorial we'll see how to style our components using CSS modules. ‍ ‍ Course Files:+ ......
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found