Get device id in react native?

Viewed 44437

how to get device id in react native. I am using create react native not android studio. I am new to this.

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

constructor(props) {
 super(props);
   this.state = { id: '' }
   this.onNavigateTo = this.onNavigateTo.bind(this);   
}
componentDidMount() {
   this.setState({id: DeviceInfo.getUniqueID()}, () =>      
   alert(this.state.id));
}
render() {
  return (
       <Text>{this.state.id}</Text>
  );
}

Error: undefined is not an object (evaluating 'RNDevice.uniqueId')

Note:- I am not using run-android or run-ios

I am using Create-react-native app and yarn start. The output will be on device through Expo app

5 Answers

If you are using Expo try this.

import Constants from 'expo-constants';
this.clientId = Constants.deviceId;

you cannot use library that use native code with expo see caveats if you want to use native code you need to create your project with native code at getting started doc basically

  1. install pre request apps (node - Java Development Kit - android studio - xcode - react native cli )
  2. run command react-native init MyProjectName
  3. cd your project folder cd MyProjectName
  4. run react-native run-android or react-native run-ios

if you want to convert expo project to native code project you can do ejecting-from-create-react-native-app

  1. install native code requirement as above
  2. run npm run eject

after that you can use third party libraries that use native code and run react-native link

If your goal is to get a client unique ID, then you might want to use NativeModules.

Import { NativeModules } from 'react-native'

on your component...

for iOS: console.log(NativeModules.SettingsManager.clientUniqueId) for Android: console.log(NativeModules.PlatformConstants.fingerprint); (or NativeModules.PlatformConstants.serial)

Related