41 lines
1.0 KiB
JavaScript
41 lines
1.0 KiB
JavaScript
// src/ThemeContext.js
|
|
import React, { createContext, useState, useEffect } from 'react';
|
|
|
|
export const ThemeContext = createContext();
|
|
|
|
export const ThemeProvider = ({ children }) => {
|
|
const [theme, setTheme] = useState('dark');
|
|
|
|
useEffect(() => {
|
|
const savedTheme = localStorage.getItem('theme') || 'dark';
|
|
setTheme(savedTheme);
|
|
applyTheme(savedTheme);
|
|
}, []);
|
|
|
|
const applyTheme = (theme) => {
|
|
const bodyClass = document.body.classList;
|
|
if (theme === 'dark') {
|
|
bodyClass.add('dark-theme');
|
|
bodyClass.remove('light-theme');
|
|
import('./dark-theme.css');
|
|
} else {
|
|
bodyClass.add('light-theme');
|
|
bodyClass.remove('dark-theme');
|
|
import('./light-theme.css');
|
|
}
|
|
};
|
|
|
|
const toggleTheme = () => {
|
|
const newTheme = theme === 'dark' ? 'light' : 'dark';
|
|
setTheme(newTheme);
|
|
localStorage.setItem('theme', newTheme);
|
|
applyTheme(newTheme);
|
|
};
|
|
|
|
return (
|
|
<ThemeContext.Provider value={{ theme, toggleTheme }}>
|
|
{children}
|
|
</ThemeContext.Provider>
|
|
);
|
|
};
|