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.
Method | Return Type | iOS | Android | Since |
---|---|---|---|---|
getAPILevel() | number |
❌ | ✅ | 0.12.0 |
getApplicationName() | string |
✅ | ✅ | 0.14.0 |
getBatteryLevel() | Promise<number> |
✅ | ✅ | 0.18.0 |
getBrand() | string |
✅ | ✅ | 0.9.3 |
getBuildNumber() | string |
✅ | ✅ | ? |
getBundleId() | string |
✅ | ✅ | ? |
getCarrier() | string |
✅ | ✅ | 0.13.0 |
getDeviceCountry() | string |
✅ | ✅ | 0.9.0 |
getDeviceId() | string |
✅ | ✅ | 0.5.0 |
getDeviceLocale() | string |
✅ | ✅ | 0.7.0 |
getDeviceName() | string |
✅ | ✅ | ? |
getFirstInstallTime() | number |
❌ | ✅ | 0.12.0 |
getFontScale() | number |
✅ | ✅ | 0.15.0 |
getFreeDiskStorage() | number |
✅ | ✅ | 0.15.0 |
getIPAddress() | Promise<string> |
✅ | ✅ | 0.12.0 |
getInstallReferrer() | string |
❌ | ✅ | 0.19.0 |
getInstanceID() | string |
❌ | ✅ | ? |
getLastUpdateTime() | number |
❌ | ✅ | 0.12.0 |
getMACAddress() | Promise<string> |
✅ | ✅ | 0.12.0 |
getManufacturer() | string |
✅ | ✅ | ? |
getMaxMemory() | number |
❌ | ✅ | 0.14.0 |
getModel() | string |
✅ | ✅ | ? |
getPhoneNumber() | string |
❌ | ✅ | 0.12.0 |
getReadableVersion() | string |
✅ | ✅ | ? |
getSerialNumber() | string |
❌ | ✅ | 0.12.0 |
getSystemName() | string |
✅ | ✅ | ? |
getSystemVersion() | string |
✅ | ✅ | ? |
getTimezone() | string |
✅ | ✅ | ? |
getTotalDiskCapacity() | number |
✅ | ✅ | 0.15.0 |
getTotalMemory() | number |
✅ | ✅ | 0.14.0 |
getUniqueID() | string |
✅ | ✅ | ? |
getUserAgent() | string |
✅ | ✅ | 0.7.0 |
getVersion() | string |
✅ | ✅ | ? |
is24Hour() | boolean |
✅ | ✅ | 0.13.0 |
isAirPlaneMode() | Promise<boolean> |
❌ | ✅ | 0.25.0 |
isEmulator() | boolean |
✅ | ✅ | ? |
isPinOrFingerprintSet() | (callback)boolean |
✅ | ✅ | 0.10.1 |
isTablet() | boolean |
✅ | ✅ | ? |
hasNotch() | boolean |
✅ | ✅ | 0.23.0 |
isLandscape() | boolean |
✅ | ✅ | 0.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 a limited amount of device information using constants and hook for all the details you should use sync/async way to access the data.
In this example, we have covered almost every piece of information that 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 command line interface to make our React Native App.
If you have previously installed a global react-native-cli package, please remove it as it may cause unexpected issues:
npm uninstall -g react-native-cli @react-native-community/cli
Run the following commands to create a new React Native project
npx react-native init ProjectName
If you want to start a new project with a specific React Native version, you can use the --version argument:
npx react-native init ProjectName --version X.XX.X
Note If the above command is failing, you may have old version of react-native
or react-native-cli
installed globally on your pc. Try uninstalling the cli and run the cli using npx.
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
Please use the following command to install CocoaPods
npx pod-install
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.
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
1. Start Metro Bundler
First, you will need to start Metro, the JavaScript bundler that ships with React Native. To start Metro bundler run following command:
npx react-native start
Once you start Metro Bundler it will run forever on your terminal until you close it. Let Metro Bundler run in its own terminal. Open a new terminal and run the application.
2. Start React Native Application
To run the project on an Android Virtual Device or on real debugging device:
npx react-native run-android
or on the iOS Simulator by running (macOS only)
npx react-native run-ios
Output Screenshots
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. 🙂
You save my day buddy. I’m very impressed for this site.
Thanx buddy. 🙂
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?
Hell Safi, Thanks for your words 🙂
Instead of printing variable like alert(x) you have to use alert(JSON.stringify(x))
It will then print the JSON in a proper format.
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
Can you please open the project in Android Studio for once? You will see the updates in the studio, Once you update the studio this issue will be resolved.