Introduction

Hello Everyone, in this article, we will explore how we could get React Native Contacts from the user phone book.

For this example we will use React Native Expo to access the phone’s contacts system, to get the list of contacts, we can also edit and delete them.

Similar to some of the famous apps use the user’s contacts.

You could add a functionality in your app to ask the user to invite his friends from his contacts list.


Or if you are developing an alternative messenger app, getting the users’ contact might be a core function to add.

Environment Setup

If you haven’t created a React Native Expo project already, you can do it right now.

Simply run this command

expo init new-app

Next, we need to install the Expo contacts API which will provide us with all the tools needed to access and manipulate the contacts system.

expo install expo-contacts

Contacts Basic Usage

Before we can access the Contacts system, there is one important step to take care of.

In order to access the list of contacts, we need to get the CONTACTS permission from our user.

So we need to handle this permission granting and denying properly.

Getting Contacts list

import React, { useEffect, useState} from 'react';
import * as Contacts from 'expo-contacts';
import { StyleSheet, View, Text, FlatList } from 'react-native'

export default function App() {
  const [contacts, setContacts ] = useState([])
  useEffect(() => {
    (async () => {
      const { status } = await Contacts.requestPermissionsAsync();
      if (status === 'granted') {
        const { data } = await Contacts.getContactsAsync({
          fields: [Contacts.Fields.PhoneNumbers],
        });

        if (data.length > 0) {
          setContacts(data)
        }
      }
    })();
  }, []);

  return (
    <View style={styles.container}>
      <FlatList 
        data={contacts}
        renderItem={({item}) => {
          return (
            <Text>{`${item.name} (${item.phoneNumbers ? item.phoneNumbers[0].number : ''})`}</Text>
          )
        }}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

As you might have noticed, we have imported the expo-contacts we have just installed at the top.

Then we created a simple state variable to store the list of contacts via the useState hook.

Next we will be using the useEffect hook to handle getting the contacts list from the system.

Starting by asking from the permission Contacts.requestPermissionsAsync(), and continue once it’s granted only.
You could go a bit further and display a text message to let the user know, he/she needs permission if it doesn’t exist or he/she denied it before.

Next we can access the contacts via Contacts.getContactsAsync()

The argument we are adding is the Contact Query, it will return the list of contacts based on it, if it’s null, it will return all that exists.

We can query using

NameTypeDescriptioniOSAndroid
fieldsFieldType[]If available the fields defined will be returned. If nil then all fields will be returned.
pageSizenumberThe max number of contacts to return. If nil or 0 then all contacts will be returned.
pageOffsetnumberThe number of contacts to skip before gathering contacts.
idstringGet contacts with a matching ID .
sortSortTypeSort method used when gathering contacts.
namestringGet all contacts whose name contains the provided string (not case-sensitive).
groupIdstringGet all contacts that belong to the group matching this ID.
containerIdstringGet all contacts that belong to the container matching this ID.
rawContactsbooleanPrevent unification of contacts when gathering. Default: false.

The return result looks like this.

{
   "contactType": "person",
   "firstName": "User Name",
   "id": "351",
   "imageAvailable": false,
   "lookupKey": "161A368D-D614-4A15-8DC6-665FDBCFAE55",
   "name": "User Name",
   "phoneNumbers": [
   {"label": "mobile", "type": "2", "id": "1601", "isPrimary": 0, "number": "+1 23456789"},
   {"label": "mobile", "type": "2", "id": "1120", "isPrimary": 0, "number": "+2 09876543"}
   ]
 }

And finally we are rendering the list of contacts using a Flatlist in our render method.

Adding Contacts

Adding a new contact to the user contacts list.

const contact = {   [Contacts.Fields.FirstName]: 'John',   [Contacts.Fields.LastName]: 'Doe',   [Contacts.Fields.Company]: 'React Native Master', }; 
const contactId = await Contacts.addContactAsync(contact);

Remove Contact

Removing a contact from the user contact system.

await Contacts.removeContactAsync('161A368D-D614-4A15-8DC6-665FDBCFAE55'); 

Conclusion

There you have it, a quick explanation of the React Native Contacts, I hope you enjoyed reading this article and found it as informative as you have expected.

I have shared the code of this project on github and expo.io, feel free to use it at your will.
Stay tuned and happy coding.