I have a context where I define my light and dark theme. Then I send the context to app where I defined a state that is passed to my Settings screen via my context provider value.
Here is my questions: If I want to toggle between dark and light via settings, where would I need to put my state? Or can I just define a function in App that I pass down via navigation somehow?
And my buttons that should toggle the theme are simple onPress buttons in the screen Settings.js, also my theme colors are already imported there via context obviously!
Please help!
App.js
import ThemeContext, {themes} from './contexts/ThemeContext';
const App = () => {
const [selectedTheme, setSelectedTheme] = useState(themes.light)
return (
<ThemeContext.Provider value={selectedTheme}>
<Stack.Navigator>
<Stack.Screen name="Settings" component={Settings}/>
</Stack.Navigator>
</ThemeContext.Provider>
);
};
ThemeContext.js
import React from "react";
export const themes = {
dark: {
background:{backgroundColor:"black"},
text:{backgroundColor:"white"},
},
light:{
background:{backgroundColor:"white"},
text:{backgroundColor:"black"},
},
}
const ThemeContext = React.createContext(themes.dark)
export default ThemeContext
>Solution :
Add "setSelectedTheme" to your Context-Provider.
<ThemeContext.Provider value={{selectedTheme, setSelectedTheme}}>
You can than import your ThemeContext in the Compontens you need it and use it this way:
const currentTheme = useContext(ThemeContext)
If you want to change the Theme, you can than use:
currentTheme.setSelectedTheme = "light"
wherever you need it.