aboutsummaryrefslogtreecommitdiff
path: root/src/ThemeContext.tsx
diff options
context:
space:
mode:
authorAriel Costas Guerrero <94913521+arielcostas@users.noreply.github.com>2025-03-03 22:54:36 +0100
committerAriel Costas Guerrero <94913521+arielcostas@users.noreply.github.com>2025-03-03 22:54:36 +0100
commit2e90c813d0cf924bb9e8b383c1202aae15b14684 (patch)
treed7dac941a482a8f0ef82645d0ffd05e1efc68e5e /src/ThemeContext.tsx
parent797c5f551b1bb6ddb139704eb9e8953c3bc1a8c8 (diff)
Add theme provider and errorBoundary
Diffstat (limited to 'src/ThemeContext.tsx')
-rw-r--r--src/ThemeContext.tsx44
1 files changed, 44 insertions, 0 deletions
diff --git a/src/ThemeContext.tsx b/src/ThemeContext.tsx
new file mode 100644
index 0000000..203b70a
--- /dev/null
+++ b/src/ThemeContext.tsx
@@ -0,0 +1,44 @@
+import { createContext, useContext, useEffect, useState, ReactNode } from 'react';
+
+type Theme = 'light' | 'dark';
+
+interface ThemeContextProps {
+ theme: Theme;
+ toggleTheme: () => void;
+}
+
+const ThemeContext = createContext<ThemeContextProps | undefined>(undefined);
+
+export const ThemeProvider = ({ children }: { children: ReactNode }) => {
+ const [theme, setTheme] = useState<Theme>(() => {
+ const savedTheme = localStorage.getItem('theme');
+ if (savedTheme) {
+ return savedTheme as Theme;
+ }
+ const prefersDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
+ return prefersDark ? 'dark' : 'light';
+ });
+
+ useEffect(() => {
+ document.documentElement.setAttribute('data-theme', theme);
+ localStorage.setItem('theme', theme);
+ }, [theme]);
+
+ const toggleTheme = () => {
+ setTheme((prevTheme) => (prevTheme === 'light' ? 'dark' : 'light'));
+ };
+
+ return (
+ <ThemeContext.Provider value={{ theme, toggleTheme }}>
+ {children}
+ </ThemeContext.Provider>
+ );
+};
+
+export const useTheme = () => {
+ const context = useContext(ThemeContext);
+ if (!context) {
+ throw new Error('useTheme must be used within a ThemeProvider');
+ }
+ return context;
+}; \ No newline at end of file