This repository has no description
0

Configure Feed

Select the types of activity you want to include in your feed.

at master 1.5 kB View raw
1// src/contexts/ThemeContext.jsx 2 3import React, { createContext, useState, useEffect } from 'react'; 4 5// Create the ThemeContext with default value 6export const ThemeContext = createContext(); 7 8export const ThemeProvider = ({ children }) => { 9 // Initialize theme based on user's system preference or localStorage 10 const [isDarkMode, setIsDarkMode] = useState(() => { 11 const savedTheme = localStorage.getItem('isDarkMode'); 12 if (savedTheme !== null) { 13 return JSON.parse(savedTheme); 14 } 15 // Fallback to system preference 16 return window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches; 17 }); 18 19 // Toggle the theme and save preference to localStorage 20 const toggleDarkMode = () => { 21 setIsDarkMode((prevMode) => { 22 localStorage.setItem('isDarkMode', JSON.stringify(!prevMode)); 23 return !prevMode; 24 }); 25 }; 26 27 // Optional: Listen to system theme changes 28 useEffect(() => { 29 const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)'); 30 const handleChange = (e) => { 31 setIsDarkMode(e.matches); 32 }; 33 mediaQuery.addEventListener('change', handleChange); 34 return () => mediaQuery.removeEventListener('change', handleChange); 35 }, []); 36 37 return ( 38 <ThemeContext.Provider value={{ isDarkMode, toggleDarkMode }}> 39 {/* Apply a class to the body based on the theme */} 40 <div className={isDarkMode ? 'dark-mode' : 'light-mode'}> 41 {children} 42 </div> 43 </ThemeContext.Provider> 44 ); 45};