Get device id in react native?

user1731387 picture user1731387 · Sep 27, 2017 · Viewed 38k times · Source

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

Answer

rahul.sapkal23 picture rahul.sapkal23 · Nov 28, 2017

Instead of expo you can create a project using react-native CLI.

Create a new project using command :

react-native init Myproject

cd Myproject

Run the project using the following command :

react-native run-android

Then you can use react-native-device-info package.

I tried with following versions and it worked for me.

  "react": "16.0.0",
  "react-native": "0.50.4",
  "react-native-device-info": "^0.12.1",

I installed it with command :

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

Then I link it with command :

react-native link react-native-device-info

If you are facing any issue while linking the package then you can do the manual link or you can cross check the packages is successfully link or not.

  1. in android/app/build.gradle:
 dependencies {
        ...
        compile "com.facebook.react:react-native:+"  // From node_modules
    +   compile project(':react-native-device-info')
    }
  1. in android/settings.gradle:

...

include ':app'

include ':react-native-device-info'

project(':react-native-device-info').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-device-info/android')

  1. in MainApplication.java:
+ import com.learnium.RNDeviceInfo.RNDeviceInfo;

  public class MainApplication extends Application implements ReactApplication {
    //......

    @Override
    protected List<ReactPackage> getPackages() {
      return Arrays.<ReactPackage>asList(
+         new RNDeviceInfo(),
          new MainReactPackage()
      );
    }

    ......
  }

Permissions

Add the appropriate, optional permissions to your AndroidManifest.xml:

...
<uses-permission android:name="android.permission.BLUETOOTH"/>         <!-- for Device Name -->
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>  <!-- for Phone Number -->

Example

var DeviceInfo = require('react-native-device-info');
// or import DeviceInfo from 'react-native-device-info';

var deviceId = DeviceInfo.getUniqueID();

you can use above deviceId.