Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Change theme in React via context

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading