Build a Dark Mode Switch in React Native ๐Ÿš€

Khan Hasan RazaKhan Hasan Raza
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

  1. What It Shows
    The app displays a message: "Hello World" and a button.

  2. 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.

  3. 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

Khan Hasan Raza
Khan Hasan Raza