Access Device’s Contact List in React Native App

Access Contact List in React Native

In this example, we will see how to access the contact list in React Native. Accessing the contact list is so easy in React Native using react-native-contacts library. This library provides a Contacts component that can help you to access the contact list, add or update any contact and can open the contact menu. Below is the list of APIs provided by this library

Contact APIs

  • getAll Promise<Contact[]> – returns all contacts as an array of objects
  • getAllWithoutPhotos – same as getAll on Android, but on iOS it will not return URIs for contact photos (because there’s a significant overhead in creating the images)
  • getContactById(contactId) –  contact with defined contactId (or null if it doesn’t exist)
  • getCount() –  number of contacts
  • getPhotoForId(contactId) –  URI (or null) for a contact’s photo
  • addContact (contact) – adds a contact to the AddressBook.
  • openContactForm (contact) – create a new contact and display in contactsUI.
  • openExistingContact (contact) – where contact is an object with a valid recordID
  • updateContact (contact) – where contact is an object with a valid recordID
  • deleteContact (contact) – where contact is an object with a valid recordID
  • getContactsMatchingString (string) – where string is any string to match a name (first, middle, family) to
  • getContactsByPhoneNumber (string) – where string is a phone number to match to.
  • getContactsByEmailAddress (string) – where string is an email address to match to.
  • checkPermission () – checks permission to access Contacts ios only
  • requestPermission () – request permission to access Contacts ios only
  • writePhotoToPath () – writes the contact photo to a given path android only

Accessing the Contact List

In this example, we will only talk about the listing of the device’s contact in our React Native app. Here is the code snippet which will help us to access the contact list.

Contacts.getAll() 
    .then(contacts => {
        contacts.sort((a, b) => 
           a.givenName.toLowerCase() > b.givenName.toLowerCase()
        ); 
        setContacts(contacts); 
    })
    .catch(e => { 
        alert('Permission to access contacts was denied'); 
        console.warn('Permission to access contacts was denied'); 
    });

I have used the getAll API which will provide all the contact lists at once. getAll is a database-intensive process, and can take a long time to complete depending on the size of the contacts list. Because of this, it is recommended you access the getAll method before it is needed, and cache the results for future use.

Project Overview

In this example, we will create a list of the device’s contacts with a search bar to filter the contact, and on clicking that contact, we will open the contact in the default contact menu.

After the launch of the screen, we will check for the platform, and if it is Android we will ask for the runtime permission and then will call loadContacts function else for iOS we will directly call loadContacts function. This loadContacts function will access the device’s contact list and will provide the same as Promise. After getting the contacts we will sort the list from A to Z

contacts.sort((a, b) =>
  a.givenName.toLowerCase() > b.givenName.toLowerCase()
);

Once we have the list of contact ready we will render the list in a list view.

We will have a search bar too which will help us to search the contact from the list. Users can search by mobile number or by name, for this, we will use getContactsByPhoneNumber and getContactsMatchingString respectively. Once the user clicks on any contact we will call openExistingContact API which will open the contact in the default contact viewer. To open any existing contact we will use

Contacts.openExistingContact(contact)

I hope you are now aware of what we are going to do. Now let’s start with the example.

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 Contacts we need to install react-native-contacts package. To install this open the terminal and jump into your project

cd ProjectName

Run the following command

npm install react-native-contacts --save

This command will copy all the dependencies into your node_module directory, You can find the directory in node_module the directory named react-native-contacts.

CocoaPods Installation

Please use the following command to install CocoaPods

npx pod-install

Android Permission to Access Contact List

We are accessing the device’s contact list which is sensitive information so we need to add some permission to the AndroidManifest.xml file. Please add the following permissions in your AndroidMnifest.xml.

Go to YourProject -> android -> app -> main -> AndroidMnifest.xml

<uses-permission android:name="android.permission.WRITE_CONTACTS"/>
<uses-permission android:name="android.permission.READ_CONTACTS"/>
Permission Purpose
WRITE_CONTACTS To Create and Update the device’s Contact details
READ_CONTACTS To Read the device’s Contact details

Contact List Permission Android
For more about the permission, you can see this post.

iOS Permission to Access Contact List

Please follow the below steps to add permission in the iOS project to access the contact list.

Open the project YourProject -> ios -> YourProject.xcworkspace in Xcode.

1. After opening the project in Xcode click on the project from the left sidebar and you will see multiple options in the workspace.

2. Select the info tab which is info.plist

3. Click on the plus button to add a permission key “Privacy-Contact Usage Description” and the value that will be visible when the permission dialog pops up.

Contact List Permission iOS

Project Structure

For example, we need to create the following directory structure. Create a components directory and then create 2 files names Avatar.js and ListItem.js in it.

Contact List Project Structure

If you have created the directory structure then you can move to the next step to replace the code in it.

Code to Access Contact List in React Native

App.js

Open App.js in any code editor and replace the code with the following code

// Access Device’s Contact List in React Native App
// https://aboutreact.com/access-contact-list-react-native/

// Import React
import React, {useState, useEffect} from 'react';

// Import all required component
import {
  PermissionsAndroid,
  Platform,
  SafeAreaView,
  StyleSheet,
  Text,
  View,
  FlatList,
  TextInput,
} from 'react-native';

import Contacts from 'react-native-contacts';
import ListItem from './components/ListItem';

const App = () => {
  let [contacts, setContacts] = useState([]);

  useEffect(() => {
    if (Platform.OS === 'android') {
      PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.READ_CONTACTS, {
          title: 'Contacts',
          message: 'This app would like to view your contacts.',
        }).then(() => {
          loadContacts();
        }
      );
    } else {
      loadContacts();
    }
  }, []);

  const loadContacts = () => {
    Contacts.getAll()
      .then(contacts => {
        contacts.sort(
          (a, b) => 
          a.givenName.toLowerCase() > b.givenName.toLowerCase(),
        );
        setContacts(contacts);
      })
      .catch(e => {
        alert('Permission to access contacts was denied');
        console.warn('Permission to access contacts was denied');
      });
  };

  const search = (text) => {
    const phoneNumberRegex = 
      /\b[\+]?[(]?[0-9]{2,6}[)]?[-\s\.]?[-\s\/\.0-9]{3,15}\b/m;
    if (text === '' || text === null) {
      loadContacts();
    } else if (phoneNumberRegex.test(text)) {
      Contacts.getContactsByPhoneNumber(text).then(contacts => {
        contacts.sort(
          (a, b) => 
          a.givenName.toLowerCase() > b.givenName.toLowerCase(),
        );
        setContacts(contacts);
        console.log('contacts', contacts);
      });
    } else {
      Contacts.getContactsMatchingString(text).then(contacts => {
        contacts.sort(
          (a, b) => 
          a.givenName.toLowerCase() > b.givenName.toLowerCase(),
        );
        setContacts(contacts);
        console.log('contacts', contacts);
      });
    }
  };

  const openContact = (contact) => {
    console.log(JSON.stringify(contact));
    Contacts.openExistingContact(contact);
  };

  return (
    <SafeAreaView style={styles.container}>
      <View style={styles.container}>
        <Text style={styles.header}>
          Access Contact List in React Native
        </Text>
        <TextInput
          onChangeText={search}
          placeholder="Search"
          style={styles.searchBar}
        />
        <FlatList
          data={contacts}
          renderItem={(contact) => {
            {
              console.log('contact -> ' + JSON.stringify(contact));
            }
            return (
              <ListItem
                key={contact.item.recordID}
                item={contact.item}
                onPress={openContact}
              />
            );
          }}
          keyExtractor={(item) => item.recordID}
        />
      </View>
    </SafeAreaView>
  );
};
export default App;

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  header: {
    backgroundColor: '#4591ed',
    color: 'white',
    paddingHorizontal: 15,
    paddingVertical: 15,
    fontSize: 20,
  },
  searchBar: {
    backgroundColor: '#f0eded',
    paddingHorizontal: 30,
    paddingVertical: Platform.OS === 'android' ? undefined : 15,
  },
});

ListItem.js

Open components/ListItem.js in any code editor and replace the code with the following code

// Access Device’s Contact List in React Native App
// https://aboutreact.com/access-contact-list-react-native/

import React, {memo} from 'react';
import {View, TouchableOpacity, Text, StyleSheet} from 'react-native';

import PropTypes from 'prop-types';
import Avatar from './Avatar';

const getAvatarInitials = (textString) => {
  if (!textString) return '';
  const text = textString.trim();
  const textSplit = text.split(' ');
  if (textSplit.length <= 1) return text.charAt(0);
  const initials =
    textSplit[0].charAt(0) + textSplit[textSplit.length - 1].charAt(0);
  return initials;
};

const ListItem = (props) => {
  const shouldComponentUpdate = () => {
    return false;
  };
  const {item, onPress} = props;
  return (
    <View>
      <TouchableOpacity onPress={() => onPress(item)}>
        <View style={styles.itemContainer}>
          <View style={styles.leftElementContainer}>
            <Avatar
              img={
                item.hasThumbnail ?
                  {uri: item.thumbnailPath} : undefined
              }
              placeholder={getAvatarInitials(
                `${item.givenName} ${item.familyName}`,
              )}
              width={40}
              height={40}
            />
          </View>
          <View style={styles.rightSectionContainer}>
            <View style={styles.mainTitleContainer}>
              <Text
                style={
                  styles.titleStyle
                }>{`${item.givenName} ${item.familyName}`}</Text>
            </View>
          </View>
        </View>
      </TouchableOpacity>
    </View>
  );
};

const styles = StyleSheet.create({
  itemContainer: {
    flexDirection: 'row',
    minHeight: 44,
    height: 63,
  },
  leftElementContainer: {
    justifyContent: 'center',
    alignItems: 'center',
    flex: 2,
    paddingLeft: 13,
  },
  rightSectionContainer: {
    marginLeft: 18,
    flexDirection: 'row',
    flex: 20,
    borderBottomWidth: StyleSheet.hairlineWidth,
    borderColor: '#515151',
  },
  mainTitleContainer: {
    justifyContent: 'center',
    flexDirection: 'column',
    flex: 1,
  },
  titleStyle: {
    fontSize: 16,
  },
});

export default memo(ListItem);

ListItem.propTypes = {
  item: PropTypes.object,
  onPress: PropTypes.func,
};

Avatar.js

Open components/Avatar.js in any code editor and replace the code with the following code

// Access Device’s Contact List in React Native App
// https://aboutreact.com/access-contact-list-react-native/

import React from 'react';
import {Image, View, Text, StyleSheet} from 'react-native';
import PropTypes from 'prop-types';

const Avatar = (props) => {
  const renderImage = () => {
    const {img, width, height, roundedImage} = props;
    const {imageContainer, image} = styles;

    const viewStyle = [imageContainer];
    if (roundedImage)
      viewStyle.push({borderRadius: Math.round(width + height) / 2});
    return (
      <View style={viewStyle}>
        <Image style={image} source={img} />
      </View>
    );
  };

  const renderPlaceholder = () => {
    const {placeholder, width, height, roundedPlaceholder} = props;
    const {placeholderContainer, placeholderText} = styles;

    const viewStyle = [placeholderContainer];
    if (roundedPlaceholder)
      viewStyle.push({borderRadius: Math.round(width + height) / 2});

    return (
      <View style={viewStyle}>
        <View style={viewStyle}>
          <Text
            adjustsFontSizeToFit
            numberOfLines={1}
            minimumFontScale={0.01}
            style={[
              {fontSize: Math.round(width) / 2},
              placeholderText
            ]}>
            {placeholder}
          </Text>
        </View>
      </View>
    );
  };

  const {img, width, height} = props;
  const {container} = styles;
  return (
    <View style={[container, props.style, {width, height}]}>
      {img ? renderImage() : renderPlaceholder()}
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    width: '100%',
  },
  imageContainer: {
    overflow: 'hidden',
    justifyContent: 'center',
    height: '100%',
  },
  image: {
    flex: 1,
    alignSelf: 'stretch',
    width: undefined,
    height: undefined,
  },
  placeholderContainer: {
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: '#dddddd',
    height: '100%',
  },
  placeholderText: {
    fontWeight: '700',
    color: '#ffffff',
  },
});

Avatar.propTypes = {
  img: Image.propTypes.source,
  placeholder: PropTypes.string,
  width: PropTypes.number.isRequired,
  height: PropTypes.number.isRequired,
  roundedImage: PropTypes.bool,
  roundedPlaceholder: PropTypes.bool,
};

Avatar.defaultProps = {
  roundedImage: true,
  roundedPlaceholder: true,
};

export default Avatar;

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

Android

Contact List Example android screenshot 1   Contact List Example android screenshot 2   Contact List Example android screenshot 3  

IOS

Contact List Example iOS screenshot 1   Contact List Example iOS screenshot 2   Contact List Example iOS screenshot 3   Contact List Example iOS screenshot 4

This is how you can access the device’s contact list in your React Native App. If you have any doubts or 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. 🙂

22 thoughts on “Access Device’s Contact List in React Native App”

  1. here in this API NOT getting all the contact details only limited details are provided. so is there any solution to get all the details?.

    Reply
    • Contact details will take some time to load all the record, Please scroll and wait for some time. If you are still unable to get the records then can you please open the contacts and find the common pattern “why these are different then others” and report it here so that I can see why it is happening.

      Reply
  2. hi…i am beginner to react native…..can we do this app in snack ……….when i put the code in snack it shows
    Cannot read property ‘getAll’ of undefined
    TypeError: Cannot read property ‘getAll’ of undefined
    at loadContacts (App.js.js:41:14

    Reply
  3. Hello, I am so grateful to you for this project, it has helped a lot. Seriously, thanks a lot sir. But While sorting the contacts array I am having some errors:
    “** TypeError: null is not an object (evaluating ‘a.givenName.toLowerCase’) **””
    Please tell me what to do. Thanks again

    Reply
  4. Hi I am using it on a simple project no expo or other third parties involved. But is still gives me error . null is not an object evaluating _reactnativeContacts.default.getAll.

    What should I do?

    Reply
  5. Hi, I also have error that error is malformed calls from JS:field sizes are different.
    After that I installed “react-native-contacts”: “^5.2.3”, but now application is crashing.
    Please tell me the accurate solution.

    Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.