Open In App

How to get user preferred color scheme in React Native ?

Last Updated : 31 Mar, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

React Native is an open-source UI software framework created by Meta Platforms, Inc. It is used to develop applications for Android, Android TV, iOS, macOS, tvOS, Web, Windows, and UWP by enabling developers to use the React framework along with native platform capabilities. 

In this article, we will be learning how we can get a user-preferred color scheme in react native.

Creating React Native App:

Step 1: We’ll be using expo to create the react native app. Install expo-cli using the below command in the terminal.

npm install -g expo-cli

Step 2: Create a react native project using expo.

expo init "gfg"

Step 3: Now go to the created project using the below command.

cd "gfg"

Project Structure: It will look like the following.

Step 4: Getting User Preferred Color Scheme: We are going to use the appearance module of react-native to determine the preferred color scheme of the user. For this add the below code inside the App.js file.

Javascript




import { StyleSheet, Text, View, Appearance,
    useColorScheme} from 'react-native';
import React, {useState , useEffect} from 'react'
  
export default function App() {
  
  const [scheme, setScheme] = useState('')
  const colorScheme = useColorScheme();
  
  useEffect(()=>{
    const userDeviceColor = Appearance.getColorScheme();
    if (userDeviceColor === 'dark') {
      setScheme('Dark Scheme')
    }else if (userDeviceColor === 'light'){
      setScheme('Light Scheme')
    }
    return
  
  })
  
  return (
    <View style={styles.container}>
      <Text>GeeksforGeeks - Color Scheme React native</Text>
      <Text>{scheme}</Text>
      <Text>colorScheme:- {colorScheme}</Text>
    </View>
  );
}
  
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'white',
    alignItems: 'center',
    justifyContent: 'center',
  },
});


Here we are using getColorScheme function of the appearance module to get the preferred color scheme of the user.

Run the application: Now run the application using the below command in the terminal.

npm run web

Output:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads