Build a Dark Mode Switch in React Native ๐

1 min read
Have you seen apps with a dark mode? It makes the screen darker, which is great for your eyes at night. This code creates a simple app where you can switch between light mode (white background) and dark mode (black background).
import React, {useState} from 'react';
import {View, Text, StyleSheet, useColorScheme, Switch} from 'react-native';
function AppPro(): JSX.Element {
const isDarkMode = useColorScheme() === 'dark';
const [darkMode, setDarkMode] = useState(isDarkMode);
function handleSwitchTheme() {
if (darkMode) {
setDarkMode(false);
} else {
setDarkMode(true);
}
}
return (
<View
style={[
styles.container,
darkMode ? styles.darkBackgroundColor : styles.whiteBackgroundColor,
]}>
<Text style={darkMode ? styles.whiteText : styles.darkText}>
Hello World
</Text>
<Switch
trackColor={{false: '#767577', true: '#81b0ff'}}
thumbColor="f4f3f4"
value={darkMode}
onValueChange={handleSwitchTheme}
/>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
darkBackgroundColor: {
backgroundColor: '#000000',
},
whiteBackgroundColor: {
backgroundColor: '#FFFFFF',
},
whiteText: {
color: '#FFFFFF',
},
darkText: {
color: '#000000',
},
});
export default AppPro;
How It Works
What It Shows
The app displays a message: "Hello World" and a button.Switch Modes
If you're in light mode, press the switch to turn on dark mode.
If you're in dark mode, press it to go back to light mode.
Colors Change
Light Mode: White background, black text.
Dark Mode: Black background, white text.
0
Subscribe to my newsletter
Read articles from Khan Hasan Raza directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
