Reputation: 929
I am creating a simple switch component that is if turned on the theme of the app will be light otherwise it would be dark.
Here is what i tried but it is not working. How can i make the toggle switch the theme of the whole app?
import { StatusBar } from 'expo-status-bar';
import React, {useState} from 'react';
import { StyleSheet, Text, View, Switch, Appearance } from 'react-native';
export default function App() {
const [isEnabled, setIsEnabled] = useState(false);
const toggleSwitch = () => setIsEnabled(previousState => !previousState);
const colorScheme = Appearance.getColorScheme();
if (colorScheme === 'dark') {
}
return (
<View style={styles.container}>
<StatusBar style="auto" />
<Switch
style={{marginBottom:500, marginLeft:150}}
trackColor={{ false: "light", true: "dark" }}
thumbColor={isEnabled ? colorScheme == 'light' : colorScheme == 'dark'}
ios_backgroundColor="#3e3e3e"
onValueChange={toggleSwitch}
value={isEnabled}
/>
</View>
);
}
Upvotes: 1
Views: 5359
Reputation: 601
Try using react-native-appearance-control
. The Appearance API in react-native is read-only, but react-native-appearance-control
provides methods for changing the underlying Color Scheme value for your app.
e.g.
import React, {useState, useEffect} from 'react';
import { Text, View, Switch, Appearance } from 'react-native';
import { setAppearanceLight, setAppearanceDark } from 'react-native-appearance-control';
export default function App() {
const [isEnabled, setIsEnabled] = useState(Appearance.getColorScheme() === 'dark');
const toggleSwitch = () => setIsEnabled(previousState => !previousState);
useEffect(()=>{
if (isEnabled) {
setAppearanceDark();
} else {
setAppearanceLight();
}
}, [isEnabled])
return (
<View>
...
<Switch
...
onValueChange={toggleSwitch}
value={isEnabled}
/>
</View>
);
}
Upvotes: 2
Reputation: 583
You can simply use useEffect here.
import { StatusBar } from 'expo-status-bar';
import React, {useState,useEffect} from 'react';
import { StyleSheet, Text, View, Switch, Appearance } from 'react-native';
export default function App() {
const [isEnabled, setIsEnabled] = useState(false);
const toggleSwitch = () => setIsEnabled(previousState => !previousState);
// add this
useEffect(()=>{
const colorScheme = Appearance.getColorScheme();
if (colorScheme === 'dark') {
setIsEnabled(true); // true means dark
}else{
setIsEnabled(false); // false means light
}
},[])
return (
<View style={styles.container}>
<StatusBar style="auto" />
<Switch
style={{marginBottom:500, marginLeft:150}}
trackColor={{ false: "light", true: "dark" }}
thumbColor={isEnabled ? colorScheme == 'light' : colorScheme == 'dark'}
ios_backgroundColor="#3e3e3e"
onValueChange={toggleSwitch}
value={isEnabled}
/>
</View>
);
}
Upvotes: 2