Sfoglia il codice sorgente

fix: dark or light theme

Apple\Apple 1 anno fa
parent
commit
9da1a72ea9
1 ha cambiato i file con 15 aggiunte e 5 eliminazioni
  1. 15 5
      src/context/Theme/index.js

+ 15 - 5
src/context/Theme/index.js

@@ -1,4 +1,4 @@
-import { createContext, useCallback, useContext, useState } from 'react';
+import { createContext, useCallback, useContext, useState, useEffect } from 'react';
 
 const ThemeContext = createContext(null);
 export const useTheme = () => useContext(ThemeContext);
@@ -9,17 +9,18 @@ export const useSetTheme = () => useContext(SetThemeContext);
 export const ThemeProvider = ({ children }) => {
   const [theme, _setTheme] = useState(() => {
     try {
-      return localStorage.getItem('theme-mode') || null;
+      return localStorage.getItem('theme-mode') || 'light';
     } catch {
-      return null;
+      return 'light';
     }
   });
 
   const setTheme = useCallback((input) => {
-    _setTheme(input ? 'dark' : 'light');
+    const newTheme = input ? 'dark' : 'light';
+    _setTheme(newTheme);
 
     const body = document.body;
-    if (!input) {
+    if (newTheme === 'light') {
       body.removeAttribute('theme-mode');
       localStorage.setItem('theme-mode', 'light');
     } else {
@@ -28,6 +29,15 @@ export const ThemeProvider = ({ children }) => {
     }
   }, []);
 
+  useEffect(() => {
+    const body = document.body;
+    if (theme === 'dark') {
+      body.setAttribute('theme-mode', 'dark');
+    } else {
+      body.removeAttribute('theme-mode');
+    }
+  }, [theme]);
+
   return (
     <SetThemeContext.Provider value={setTheme}>
       <ThemeContext.Provider value={theme}>{children}</ThemeContext.Provider>