Search code examples
reactjsstyled-componentsstitches

Dark theme does not work with React Stitches


I'm using Stitches in React to handle my CSS and theming. I have the following code:

import React from 'react'
import { createStitches, globalCss } from '@stitches/react'

const { theme, createTheme } = createStitches({
  theme: {
    colors: {
      text: 'blue',
      bodyBg: 'lightgray',
    },
  },
})

const darkTheme = createTheme('dark-theme', {
  colors: {
    bodyBg: 'black',
  },
})

const globalStyles = globalCss({
  'body': {
    color: '$text',
    backgroundColor: '$bodyBg'
  },
});

function App() {
  globalStyles()
  return (
    <div className='App'>
      <h1>Hello World!</h1>
    </div>
  )
}

export default App

As you can see, I have a default theme, and then a dark theme that extends the default theme while overriding some properties (in this case, the bodyBg). I'm applying these styles directly in my <body>. The default theme works fine, but the dark theme does not. When I add the .dark-theme class to my <html>, nothing changes (the background should turn black). What exactly am I doing wrong here?


Solution

  • You are probably trying to add the class directly to the body in the developer tools which doesn't work.

    I managed to make it work with a button onClick event:

    const darkTheme = createTheme('dark-theme', {
      colors: {
        bodyBg: 'black',
      },
    })
    
    function App() {
    
      const setBlackTheme = () => {
        document.body.classList.remove(...document.body.classList);
    
        // Here we set the darkTheme as a class to the body tag
        document.body.classList.add(darkTheme);
      }
    
      globalStyles()
      return (
        <div className='App'>
          <button onClick={setBlackTheme}>Dark Theme</button>
          <h1>Hello World!</h1>
        </div>
      )
    }
    
    export default App
    

    Try it and let's see if it works for you as well.