Example to Get Device Information in React Native

Device Information using React Native App

This is an Example to Get Device Information in React Native. To get the device information in React Native will use the react-native-device-info library.

In this example, we will show you how to get all the information about the device using a single library. We will get the following details in this example.

MethodReturn Type iOSAndroidSince
getAPILevel()number0.12.0
getApplicationName()string0.14.0
getBatteryLevel()Promise<number>0.18.0
getBrand()string0.9.3
getBuildNumber()string?
getBundleId()string?
getCarrier()string0.13.0
getDeviceCountry()string0.9.0
getDeviceId()string0.5.0
getDeviceLocale()string0.7.0
getDeviceName()string?
getFirstInstallTime()number0.12.0
getFontScale()number0.15.0
getFreeDiskStorage()number0.15.0
getIPAddress()Promise<string>0.12.0
getInstallReferrer()string0.19.0
getInstanceID()string?
getLastUpdateTime()number0.12.0
getMACAddress()Promise<string>0.12.0
getManufacturer()string?
getMaxMemory()number0.14.0
getModel()string?
getPhoneNumber()string0.12.0
getReadableVersion()string?
getSerialNumber()string0.12.0
getSystemName()string?
getSystemVersion()string?
getTimezone()string?
getTotalDiskCapacity()number0.15.0
getTotalMemory()number0.14.0
getUniqueID()string?
getUserAgent()string0.7.0
getVersion()string?
is24Hour()boolean0.13.0
isAirPlaneMode()Promise<boolean>0.25.0
isEmulator()boolean?
isPinOrFingerprintSet()(callback)boolean0.10.1
isTablet()boolean?
hasNotch()boolean0.23.0
isLandscape()boolean0.24.0
getDeviceType()string?

You can access all the above mentioned details (and many more) using this library using sync or async call, you can even get this value as a constant and can get it as a hook. The important point is you can access some limited amount of device information using constants and hook for the all the details you should use sync/async way to access the data.

In this example we have covered almost every information which you can get using this library. You will see how to access the device information using different ways (Sync, Async, Constant, Hook) in React Native using React Native Device Information library. So let’s get started with the example to Get Device Info.

To Make a React Native App

Getting started with React Native will help you to know more about the way you can make a React Native project. We are going to use react-native init to make our React Native App. Assuming that you have node installed, you can use npm to install the react-native-cli command line utility. Open the terminal and go to the workspace and run

npm install -g react-native-cli

Run the following commands to create a new React Native project

react-native init ProjectName

If you want to start a new project with a specific React Native version, you can use the --version argument:

react-native init ProjectName --version X.XX.X
react-native init ProjectName --version react-native@next

This will make a project structure with an index file named App.js in your project directory.

Installation of Dependency

To use DeviceInfo we need to install react-native-device-info dependency.

To install this open the terminal and jump into your project using

cd ProjectName

Run the following command to install

npm install react-native-device-info --save

This command will copy all the dependencies into your node_module directory, You can find the directory in node_module directory named react-native-device-info.

–save is optional, it is just to update the react-native-device-info dependency in your package.json file.

CocoaPods Installation

After the updation of React Native 0.60, they have introduced autolinking so we do not require to link the library but need to install pods. So to install pods use

cd ios && pod install && cd ..

Additional Permission for Android

To use getIPAddress in Android, you need to get permission in Android. So to get the permission, add the below line into your AndroidManifest.xml

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>

Directory Structure for Example

To start with this Example you need to create a directory named pages and four files under it with the name DeviceInfoAsync.js, DeviceInfoConstants.js, DeviceInfoHooks.js and DeviceInfoSync.js in your project. Each file has a different way to access device information in React Native.

ReactNativeDeviceInfoDirectoryStructure

app.js will be our main file and with the help of state we will hide/show these functional components.

Code to get the Device Information using React Native App

Now Open App.js in any code editor and replace the code with the following code

App.js

// Example to Get Device Information in React Native
// https://aboutreact.com/react-native-device-info/

// import React in our code
import React, {useState} from 'react';

// import all the components we are going to use
import {
  StyleSheet,
  Text,
  SafeAreaView,
  View,
  TouchableOpacity,
} from 'react-native';

import DeviceInfoAsync from './pages/DeviceInfoAsync';
import DeviceInfoConstants from './pages/DeviceInfoConstants';
import DeviceInfoSync from './pages/DeviceInfoSync';
import DeviceInfoHooks from './pages/DeviceInfoHooks';

const App = () => {
  const [activeTab, setActiveTab] = useState('constant');
  const [] = useState({});

  return (
    <SafeAreaView style={styles.container}>
      {activeTab === 'constant' ? (
        <DeviceInfoConstants
          title="React Native Device Info - Constant Info" 
        />
      ) : activeTab === 'sync' ? (
        <DeviceInfoSync
          title="React Native Device Info - Sync Info"
        />
      ) : activeTab === 'async' ? (
        <DeviceInfoAsync
          title="React Native Device Info - Device info Async"
        />
      ) : activeTab === 'hooks' ? (
        <DeviceInfoHooks
          title="React Native Device Info - Device info Hook"
        />
      ) : null}

      <View style={styles.tabBar}>
        <TouchableOpacity
          style={styles.tab}
          onPress={() => setActiveTab('constant')}>
          <Text
            style={[
              styles.tabText,
              activeTab === 'constant' && styles.boldText,
            ]}>
            Constant
          </Text>
        </TouchableOpacity>

        <TouchableOpacity
          style={styles.tab}
          onPress={() => setActiveTab('sync')}>
          <Text
            style={[
              styles.tabText,
              activeTab === 'sync' && styles.boldText
            ]}>
            Sync
          </Text>
        </TouchableOpacity>

        <TouchableOpacity
          style={styles.tab}
          onPress={() => setActiveTab('async')}>
          <Text
            style={[
              styles.tabText,
              activeTab === 'async' && styles.boldText
            ]}>
            Async
          </Text>
        </TouchableOpacity>

        <TouchableOpacity
          style={styles.tab}
          onPress={() => setActiveTab('hooks')}>
          <Text
            style={[
              styles.tabText,
              activeTab === 'hooks' && styles.boldText
            ]}>
            Hooks
          </Text>
        </TouchableOpacity>
      </View>
    </SafeAreaView>
  );
};
export default App;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#F5FCFF',
  },
  tabBar: {
    flexDirection: 'row',
    borderTopColor: '#333333',
    borderTopWidth: 1,
  },
  tab: {
    height: 50,
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
  tabText: {
    color: '#333333',
  },
  boldText: {
    fontWeight: '700',
  },
});

pages/DeviceInfoAsync.js

Open DeviceInfoAsync.js in any code editor and replace the code with the following code.

// Example to Get Device Information in React Native
// https://aboutreact.com/react-native-device-info/

// import React in our code
import React, {useState, useEffect} from 'react';

// import all the components we are going to use
import {ScrollView, StyleSheet, Text} from 'react-native';

import DeviceInfo from 'react-native-device-info';

import {getManufacturer} from 'react-native-device-info';

const DeviceInfoAsync = (props) => {
  const [asyncDeviceInfo, setAsyncDeviceInfo] = useState({});

  useEffect(() => {
    getDataAsync();
  }, []);

  const getDataAsync = async () => {
    let deviceJSON = {};
    try {
      deviceJSON.manufacturer = await getManufacturer();
      deviceJSON.buildId = await DeviceInfo.getBuildId();
      deviceJSON.isCameraPresent = 
        await DeviceInfo.isCameraPresent();
      deviceJSON.deviceName = await DeviceInfo.getDeviceName();
      deviceJSON.usedMemory = await DeviceInfo.getUsedMemory();
      deviceJSON.userAgent = await DeviceInfo.getUserAgent();
      deviceJSON.instanceId = await DeviceInfo.getInstanceId();
      deviceJSON.installReferrer = 
        await DeviceInfo.getInstallReferrer();
      deviceJSON.installerPackageName = 
        await DeviceInfo.getInstallerPackageName();
      deviceJSON.isEmulator = await DeviceInfo.isEmulator();
      deviceJSON.fontScale = await DeviceInfo.getFontScale();
      deviceJSON.hasNotch = await DeviceInfo.hasNotch();
      deviceJSON.firstInstallTime = 
        await DeviceInfo.getFirstInstallTime();
      deviceJSON.lastUpdateTime = 
        await DeviceInfo.getLastUpdateTime();
      deviceJSON.serialNumber = 
        await DeviceInfo.getSerialNumber();
      deviceJSON.androidId = await DeviceInfo.getAndroidId();
      deviceJSON.IpAddress = await DeviceInfo.getIpAddress();
      // For MacAddress add android.permission.ACCESS_WIFI_STATE
      deviceJSON.MacAddress = await DeviceInfo.getMacAddress();
      // For phoneNumber add android.permission.READ_PHONE_STATE
      deviceJSON.phoneNumber = await DeviceInfo.getPhoneNumber();
      deviceJSON.ApiLevel = await DeviceInfo.getApiLevel();
      deviceJSON.carrier = await DeviceInfo.getCarrier();
      deviceJSON.totalMemory = await DeviceInfo.getTotalMemory();
      deviceJSON.maxMemory = await DeviceInfo.getMaxMemory();
      deviceJSON.totalDiskCapacity = 
        await DeviceInfo.getTotalDiskCapacity();
      deviceJSON.totalDiskCapacityOld = 
        await DeviceInfo.getTotalDiskCapacityOld();
      deviceJSON.freeDiskStorage = 
        await DeviceInfo.getFreeDiskStorage();
      deviceJSON.freeDiskStorageOld = 
        await DeviceInfo.getFreeDiskStorageOld();
      deviceJSON.batteryLevel = await DeviceInfo.getBatteryLevel();
      deviceJSON.isLandscape = await DeviceInfo.isLandscape();
      deviceJSON.isAirplaneMode = await DeviceInfo.isAirplaneMode();
      deviceJSON.isBatteryCharging = 
        await DeviceInfo.isBatteryCharging();
      deviceJSON.isPinOrFingerprintSet = 
        await DeviceInfo.isPinOrFingerprintSet();
      deviceJSON.supportedAbis = await DeviceInfo.supportedAbis();
      deviceJSON.hasSystemFeature = 
        await DeviceInfo.hasSystemFeature(
          'android.software.webview',
        );
      deviceJSON.getSystemAvailableFeatures = 
        await DeviceInfo.getSystemAvailableFeatures();
      deviceJSON.powerState = await DeviceInfo.getPowerState();
      deviceJSON.isLocationEnabled = 
        await DeviceInfo.isLocationEnabled();
      deviceJSON.headphones = 
        await DeviceInfo.isHeadphonesConnected();
      deviceJSON.getAvailableLocationProviders = 
        await DeviceInfo.getAvailableLocationProviders();
      deviceJSON.bootloader = await DeviceInfo.getBootloader();
      deviceJSON.device = await DeviceInfo.getDevice();
      deviceJSON.display = await DeviceInfo.getDisplay();
      deviceJSON.fingerprint = await DeviceInfo.getFingerprint();
      deviceJSON.hardware = await DeviceInfo.getHardware();
      deviceJSON.host = await DeviceInfo.getHost();
      deviceJSON.product = await DeviceInfo.getProduct();
      deviceJSON.tags = await DeviceInfo.getTags();
      deviceJSON.type = await DeviceInfo.getType();
      deviceJSON.baseOS = await DeviceInfo.getBaseOs();
      deviceJSON.previewSdkInt = 
        await DeviceInfo.getPreviewSdkInt();
      deviceJSON.securityPatch = 
        await DeviceInfo.getSecurityPatch();
      deviceJSON.codename = await DeviceInfo.getCodename();
      deviceJSON.incremental = await DeviceInfo.getIncremental();
      deviceJSON.supported32BitAbis = 
        await DeviceInfo.supported32BitAbis();
      deviceJSON.supported64BitAbis = 
        await DeviceInfo.supported64BitAbis();
      deviceJSON.synchronizedUniqueId = 
        await DeviceInfo.syncUniqueId();
      try {
        deviceJSON.deviceToken = await DeviceInfo.getDeviceToken();
      } catch (e) {
        console.log(
          'Unable to get device token.
           Either simulator or not iOS11+',
        );
      }
    } catch (e) {
      console.log('Trouble getting device info ', e);
    }
    // eslint-disable-next-line react/no-did-mount-set-state
    setAsyncDeviceInfo(deviceJSON);
  };

  return (
    <>
      <Text style={styles.titleStyle}>{props.title}</Text>
      <ScrollView>
        <Text style={styles.instructions}>
          {JSON.stringify(asyncDeviceInfo, null, '  ')}
        </Text>
      </ScrollView>
    </>
  );
};
export default DeviceInfoAsync;

const styles = StyleSheet.create({
  titleStyle: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'left',
    color: '#333333',
    margin: 5,
  },
});

pages/DeviceInfoConstants.js

Open DeviceInfoConstants.js in any code editor and replace the code with the following code.

// Example to Get Device Information in React Native
// https://aboutreact.com/react-native-device-info/

// import React in our code
import React from 'react';

// import all the components we are going to use
import {ScrollView, StyleSheet, Text} from 'react-native';

import DeviceInfo from 'react-native-device-info';

const DeviceInfoConstants = (props) => {
  let deviceJSON = {};
  deviceJSON.uniqueId = DeviceInfo.getUniqueId();
  deviceJSON.deviceId = DeviceInfo.getDeviceId();
  deviceJSON.bundleId = DeviceInfo.getBundleId();
  deviceJSON.systemName = DeviceInfo.getSystemName();
  deviceJSON.systemVersion = DeviceInfo.getSystemVersion();
  deviceJSON.version = DeviceInfo.getVersion();
  deviceJSON.readableVersion = DeviceInfo.getReadableVersion();
  deviceJSON.buildNumber = DeviceInfo.getBuildNumber();
  deviceJSON.isTablet = DeviceInfo.isTablet();
  deviceJSON.appName = DeviceInfo.getApplicationName();
  deviceJSON.brand = DeviceInfo.getBrand();
  deviceJSON.model = DeviceInfo.getModel();
  deviceJSON.deviceType = DeviceInfo.getDeviceType();

  return (
    <>
      <Text style={styles.titleStyle}>{props.title}</Text>
      <ScrollView>
        <Text style={styles.instructions}>
          {JSON.stringify(deviceJSON, null, '  ')}
        </Text>
      </ScrollView>
    </>
  );
};
export default DeviceInfoConstants;

const styles = StyleSheet.create({
  titleStyle: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'left',
    color: '#333333',
    margin: 5,
  },
});

pages/DeviceInfoHooks.js

Open DeviceInfoHooks.js in any code editor and replace the code with the following code.

// Example to Get Device Information in React Native
// https://aboutreact.com/react-native-device-info/

// import React in our code
import React from 'react';

// import all the components we are going to use
import {ScrollView, StyleSheet, Text} from 'react-native';

import {
  useBatteryLevel,
  useBatteryLevelIsLow,
  usePowerState,
  useFirstInstallTime,
  useDeviceName,
  useHasSystemFeature,
  useIsEmulator,
} from 'react-native-device-info';

const DeviceInfoHooks = (props) => {
  const batteryLevel = useBatteryLevel();
  const batteryLevelIsLow = useBatteryLevelIsLow();
  const powerState = usePowerState();
  const firstInstallTime = useFirstInstallTime();
  const deviceName = useDeviceName();
  const hasSystemFeature = 
    useHasSystemFeature('amazon.hardware.fire_tv');
  const isEmulator = useIsEmulator();
  const deviceJSON = {
    batteryLevel,
    batteryLevelIsLow,
    powerState,
    firstInstallTime,
    deviceName,
    hasSystemFeature,
    isEmulator,
  };
  return (
    <>
      <Text style={styles.titleStyle}>{props.title}</Text>
      <ScrollView>
        <Text style={styles.instructions}>
          {JSON.stringify(deviceJSON, null, '  ')}
        </Text>
      </ScrollView>
    </>
  );
};
export default DeviceInfoHooks;

const styles = StyleSheet.create({
  titleStyle: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'left',
    color: '#333333',
    margin: 5,
  },
});

pages/DeviceInfoSync.js

Open DeviceInfoSync.js in any code editor and replace the code with the following code.

// Example to Get Device Information in React Native
// https://aboutreact.com/react-native-device-info/

// import React in our code
import React from 'react';

// import all the components we are going to use
import {ScrollView, StyleSheet, Text} from 'react-native';

import DeviceInfo, {getManufacturerSync} from 'react-native-device-info';

const DeviceInfoSync = (props) => {
  let deviceJSON = {};
  deviceJSON.manufacturer = getManufacturerSync();
  deviceJSON.buildId = DeviceInfo.getBuildIdSync();
  deviceJSON.isCameraPresent = DeviceInfo.isCameraPresentSync();
  deviceJSON.deviceName = DeviceInfo.getDeviceNameSync();
  deviceJSON.usedMemory = DeviceInfo.getUsedMemorySync();
  deviceJSON.instanceId = DeviceInfo.getInstanceIdSync();
  deviceJSON.installReferrer = DeviceInfo.getInstallReferrerSync();
  deviceJSON.installerPackageName = 
    DeviceInfo.getInstallerPackageNameSync();
  deviceJSON.isEmulator = DeviceInfo.isEmulatorSync();
  deviceJSON.fontScale = DeviceInfo.getFontScaleSync();
  deviceJSON.hasNotch = DeviceInfo.hasNotch();
  deviceJSON.firstInstallTime = 
    DeviceInfo.getFirstInstallTimeSync();
  deviceJSON.lastUpdateTime = DeviceInfo.getLastUpdateTimeSync();
  deviceJSON.serialNumber = DeviceInfo.getSerialNumberSync();
  deviceJSON.androidId = DeviceInfo.getAndroidIdSync();
  deviceJSON.IpAddress = DeviceInfo.getIpAddressSync();
  // needs android.permission.ACCESS_WIFI_STATE
  deviceJSON.MacAddress = 
    DeviceInfo.getMacAddressSync();
  // needs android.permission.READ_PHONE_STATE
  deviceJSON.phoneNumber = DeviceInfo.getPhoneNumberSync();
  deviceJSON.ApiLevel = DeviceInfo.getApiLevelSync();
  deviceJSON.carrier = DeviceInfo.getCarrierSync();
  deviceJSON.totalMemory = DeviceInfo.getTotalMemorySync();
  deviceJSON.maxMemory = DeviceInfo.getMaxMemorySync();
  deviceJSON.totalDiskCapacity = 
    DeviceInfo.getTotalDiskCapacitySync();
  deviceJSON.totalDiskCapacityOld = 
    DeviceInfo.getTotalDiskCapacityOldSync();
  deviceJSON.freeDiskStorage = DeviceInfo.getFreeDiskStorageSync();
  deviceJSON.freeDiskStorageOld = 
    DeviceInfo.getFreeDiskStorageOldSync();
  deviceJSON.batteryLevel = DeviceInfo.getBatteryLevelSync();
  deviceJSON.isLandscape = DeviceInfo.isLandscapeSync();
  deviceJSON.isAirplaneMode = DeviceInfo.isAirplaneModeSync();
  deviceJSON.isBatteryCharging = DeviceInfo.isBatteryChargingSync();
  deviceJSON.isPinOrFingerprintSet =
    DeviceInfo.isPinOrFingerprintSetSync();
  deviceJSON.supportedAbis = DeviceInfo.supportedAbisSync();
  deviceJSON.hasSystemFeature = 
    DeviceInfo.hasSystemFeatureSync(
      'android.software.webview',
    );
  deviceJSON.getSystemAvailableFeatures = 
    DeviceInfo.getSystemAvailableFeaturesSync();
  deviceJSON.powerState = DeviceInfo.getPowerStateSync();
  deviceJSON.isLocationEnabled = 
    DeviceInfo.isLocationEnabledSync();
  deviceJSON.headphones = DeviceInfo.isHeadphonesConnectedSync();
  deviceJSON.getAvailableLocationProviders = 
    DeviceInfo.getAvailableLocationProvidersSync();
  deviceJSON.bootloader = DeviceInfo.getBootloaderSync();
  deviceJSON.device = DeviceInfo.getDeviceSync();
  deviceJSON.display = DeviceInfo.getDisplaySync();
  deviceJSON.fingerprint = DeviceInfo.getFingerprintSync();
  deviceJSON.hardware = DeviceInfo.getHardwareSync();
  deviceJSON.host = DeviceInfo.getHostSync();
  deviceJSON.product = DeviceInfo.getProductSync();
  deviceJSON.tags = DeviceInfo.getTagsSync();
  deviceJSON.type = DeviceInfo.getTypeSync();
  deviceJSON.baseOS = DeviceInfo.getBaseOsSync();
  deviceJSON.previewSdkInt = DeviceInfo.getPreviewSdkIntSync();
  deviceJSON.securityPatch = DeviceInfo.getSecurityPatchSync();
  deviceJSON.codename = DeviceInfo.getCodenameSync();
  deviceJSON.incremental = DeviceInfo.getIncrementalSync();
  deviceJSON.supported32BitAbis = 
    DeviceInfo.supported32BitAbisSync();
  deviceJSON.supported64BitAbis = 
    DeviceInfo.supported64BitAbisSync();

  return (
    <>
      <Text style={styles.titleStyle}>{props.title}</Text>
      <ScrollView>
        <Text style={styles.instructions}>
          {JSON.stringify(deviceJSON, null, '  ')}
        </Text>
      </ScrollView>
    </>
  );
};
export default DeviceInfoSync;

const styles = StyleSheet.create({
  titleStyle: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'left',
    color: '#333333',
    margin: 5,
  },
});

To Run the React Native App

Open the terminal again and jump into your project using.

cd ProjectName

To run the project on an Android Virtual Device or on real debugging device

react-native run-android

or on the iOS Simulator by running (macOS only)

react-native run-ios

Download Source Code

Output Screenshots

ReactNativeDeviceInfoScreenshot1   ReactNativeDeviceInfoScreenshot2   ReactNativeDeviceInfoScreenshot3   ReactNativeDeviceInfoScreenshot4

This is how you can get the Device Info. If you have any doubts or you want to share something about the topic you can comment below or contact us here. There will be more posts coming soon. Stay tuned!

Hope you liked it. 🙂


Related Posts

5 thoughts on “Example to Get Device Information in React Native”

  1. First of all, thanks a lot for the tutorial, such tutorials really help for beginners.

    Secondly, when I tried to implement the code, it doesn’t show the information for me. It just shows [object Object] in place of the info. Any clue how to solve this?

    Reply
  2. I am using React Navigation 5 and after installing this libraries i got this exception :
    Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0

    Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.