ExpoStartup
Theming

ThemeToggle

A component that allows users to switch between light and dark modes.

ThemeToggle

The ThemeToggle component provides an animated button that allows users to toggle between light and dark themes.

Import

import ThemeToggle from '@/components/ThemeToggle';

Features

  • Smooth animation when toggling between themes
  • Automatically displays the correct icon based on current theme
  • Can be used in controlled or uncontrolled mode
  • Automatically integrates with the app's theme context

Props

PropTypeDefaultDescription
valuebooleanCurrent theme stateOptional controlled mode value
onChange(value: boolean) => voidToggle themeOptional callback for controlled mode

Basic Usage

// Simple usage with automatic theme integration
<ThemeToggle />
 
// Using in a header
<View className="flex-row justify-between items-center p-4">
  <ThemedText className="text-xl font-bold">App Title</ThemedText>
  <ThemeToggle />
</View>

Controlled Mode

The component can also be used in controlled mode, where you manage the state yourself:

import React, { useState } from 'react';
import { View } from 'react-native';
import ThemeToggle from '@/components/ThemeToggle';
import ThemedText from '@/components/ThemedText';
 
function MyComponent() {
  const [isDarkMode, setIsDarkMode] = useState(false);
  
  return (
    <View className="p-4">
      <View className="flex-row justify-between items-center">
        <ThemedText>Current Mode: {isDarkMode ? 'Dark' : 'Light'}</ThemedText>
        <ThemeToggle 
          value={isDarkMode}
          onChange={(value) => {
            setIsDarkMode(value);
            console.log(`Theme changed to ${value ? 'dark' : 'light'} mode`);
          }}
        />
      </View>
    </View>
  );
}

Implementation Details

The ThemeToggle component uses React Native's Animated API to create a smooth transition effect when switching between themes. It displays a sun icon for dark mode and a moon icon for light mode.

Under the hood, it uses the useTheme hook from the ThemeContext to access and modify the current theme state. When pressed, it animates a scale and rotation effect before changing the icon.

Examples

Adding to a Drawer Header

function DrawerHeader() {
  return (
    <View className="flex-row items-center justify-between p-4">
      <Avatar src="https://example.com/user.jpg" size="md" />
      <ThemeToggle />
    </View>
  );
}

Adding to Welcome Screen

function WelcomeScreen() {
  return (
    <View className="flex-1 bg-light-primary dark:bg-dark-primary">
      <View className="absolute top-8 right-4 z-10">
        <ThemeToggle />
      </View>
      <View className="flex-1 justify-center items-center p-4">
        <ThemedText className="text-2xl font-bold mb-4">
          Welcome to the App
        </ThemedText>
        {/* More content */}
      </View>
    </View>
  );
}

On this page