import React, { useContext, useState } from
'react'
;
const ThemeContext = React.createContext();
function
ThemeProvider({ children }) {
const [theme, setTheme] = useState(
'light'
);
return
(
<ThemeContext.Provider value={{ theme, setTheme }}>
{children}
</ThemeContext.Provider>
);
}
function
ThemedComponent() {
const { theme, setTheme } = useContext(ThemeContext);
const toggleTheme = () => {
setTheme(prevTheme => prevTheme ===
'light'
?
'dark'
:
'light'
);
};
return
(
<div style={{
backgroundColor: theme ===
'light'
?
'#ffffff'
:
'#333333'
, color: theme ===
'light'
?
'#000000'
:
'#ffffff'
}}>
<p>Current Theme: {theme}</p>
<button onClick={toggleTheme}>Toggle Theme</button>
</div>
);
}
function
App() {
return
(
<ThemeProvider>
<ThemedComponent />
</ThemeProvider>
);
}
export
default
App;