How to get phone contacts in the react-native application

|
| By Webner

To get phone contacts in the react-native application, it provides a package called react-native-contacts. This package provides you with all the contacts and their info from your mobile device.

Installation:

npm install react-native-contacts --save

For ios:

cd ios && pod install

Permissions:

If your app creates contacts then add WRITE_CONTACTS permission to AndroidManifest.xml and READ_CONTACTS to read the contacts.
...
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
...

Usage

First, you need to import the package to your page.
import Contacts from 'react-native-contacts';
After that, you need to add permissions for pulling contacts from your phone. For android, you can use the PermissionsAndroid API . And for ios, you need to add the permissions in the info.plist file. After adding the permissions a popup will appear to ask you for allowing that to view your phone contacts.

import React from 'react';
import { PermissionsAndroid } from 'react-native';
import Contacts from 'react-native-contacts';
export default class App extends React.Component {
constructor(props) {
super(props);
}
componentDidMount(){ // runs after component rendering
this.getContacts();
}
async getContacts(){ //function to get the contacts data using android permissions
if (Platform.OS === 'android') {
await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.READ_CONTACTS,
{
title: 'Contacts',
message: 'This app would like to view your contacts.',
},
).then(async (response) => {
if(response=='granted'){
Contacts.getAll((err, contacts) => {
if (err === 'denied') { //if user denied the permission
console.warn('Permission to access contacts was denied');
} else {
console.log(contacts); //phone contacts data as array
}
});
}
})
.catch(async (error)=>{
console.log(error);
});
} else { ///this else works in case of ios device
Contacts.getAll((err, contacts) => {
if (err === 'denied') {
console.warn('Permission to access contacts was denied');
} else {
console.log(contacts); //phone contacts data as array
}
});
}
}
}

Result:- You will get the array of the contacts in the console logs that can be used according to your requirement.

Leave a Reply

Your email address will not be published. Required fields are marked *