skip to Main Content

The problem is that my background doesn’t change and I don’t know why. I don’t get any error. My button should change the background from light to dark. I think I have done all the necessary steps for this one.

App.js

function App() {
  const [theme, setTheme] = useState("light");

  const toggleTheme = () => {
    theme === "light" ? setTheme("dark") : setTheme("light");
  };

  return (
    <ThemeProvider theme={theme === "light" ? themeLight : themeDark}>
      <GlobalStyle />
        <button onClick={toggleTheme}></button>
        <Header />
    </ThemeProvider>
  );
}

Theme.js:

export const themeLight = {
  color: {
    background: "#fff",
  },
};

export const themeDark = {
  color: {
    background: "#000",
  },
};

GlobalStyle:

export const GlobalStyle = createGlobalStyle`
  .body {
    background: ${({ theme }) => theme.color.background};
  }
`;

ThemeContext:

const ThemeContext = createContext(null);

export default ThemeContext;

I have two color object in theme.js (themeDark and themeLight). I added styles (text and backgroud) in the body. I created a ThemeContext file with createContext. I moved GlobalStyle from index.js (root) and ThemeProvider to the App.js.

2

Answers


  1. I feel that there is an issue with your app. js.

     const toggleTheme = () => {
      theme === "light" ? setTheme("dark") : setTheme("light");
    

    };

    As you can see, when your theme is light, you have set it to dark, and in the themeProvider you have checked theme is triple equal to light, so you are using themeLight styling.

    So, could you please check if you are checking in your toggleTheme function for the light theme, then set it to light only, not dark?

    Please find below the change I am suggesting that might work for you and if doesn’t work then try to console the theme which you are getting so that it can be easy for you to fix it.

     const toggleTheme = () => {
      theme === "light" ? setTheme("light") : setTheme("dark");
    

    };

    Login or Signup to reply.
  2. Just remove the dot before body in GlobalStyle and it should work.

    export const GlobalStyle = createGlobalStyle`
      body {
        background: ${({ theme }) => theme.color.background};
      }
    `;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search