Reputation: 63
I know that the app's theme changes when I switch the device's theme from light to dark or from dark to light. However, I'm looking for an easy way to do that same thing programmatically: you see, I'm trying to implement a dark mode switch that the user can toggle to change the theme; can't I just do something like onChange={() => { toggleDarkMode(); }}
?
The project I'm working on has been created by running
npx create-expo-app --template
and choosing
the Navigation (TypeScript)
template.
Upvotes: 0
Views: 39
Reputation: 63
Just solved it, 20 minutes after posting. You can easily change the theme by using Appearance.setColorScheme(...)
.
Import Appearance
and useColorScheme
from 'react-native'
, declare the colorScheme
constant and assing it useColorScheme()
; the only thing left to do is using Appearance.setColorScheme()
to change the theme. This is the final code:
import { Appearance, Switch, useColorScheme } from 'react-native';
//...
export default function SettingsScreen() {
const colorScheme = useColorScheme();
return (
<View style={styles.container}>
//...
<Switch value={colorScheme=='dark'}
onChange={() => {
Appearance.setColorScheme(colorScheme=='dark' ? 'light' : 'dark')
}}/>
//...
</View>
);
}
Upvotes: 1