How to Check whether Dark Mode is enabled in React Native

From Android 10 and iOS 13, mobile phone users can prefer to use dark mode over the default light theme. As a mobile app developer, it’s important to know the color scheme preference of the user to make changes in the app design accordingly. Let’s learn how to check the color scheme preference of users in react native.

The Appearance API from react native helps developers to identify the appearance preferences of users. It identifies the color scheme – dark or light. See the code snippet given below which shows how to check whether the dark mode is enabled.

import { Appearance } from 'react-native';

const colorScheme = Appearance.getColorScheme();
if (colorScheme === 'dark') {
  // Switch to dark theme
}

The supported color schemes are light, dark, and null. Always remember that getColorScheme() will always return light when debugging. Hence, test the Appearance API without enabling the debugger.

Alternatively, you can also use useColorScheme hook to obtain the user-selected color scheme.

import { useColorScheme } from 'react-native';

const colorScheme = useColorScheme();
if (colorScheme === 'dark') {
  // Switch to dark theme
}

Following is a complete react native example which shows whether the scheme is light or dark.

import React from 'react';
import {Text, StyleSheet, Appearance, View} from 'react-native';

const App = () => {
  const colorScheme = Appearance.getColorScheme();
  return (
    <View style={styles.container}>
      <Text>The current preferred theme: {colorScheme}</Text>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
});

export default App;

Following will be the output.

You can also make use of Context API to make a dynamic custom dark theme.

I hope this react native tutorial helps you.

Similar Posts