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 API provided by this library

Contact APIs

  • getAll (callback) – 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, callback) – returns contact with defined contactId (or null if it doesn’t exist)
  • getCount(callback) – returns the number of contacts
  • getPhotoForId(contactId, callback) – returns a URI (or null) for a contact’s photo
  • addContact (contact, callback) – adds a contact to the AddressBook.
  • openContactForm (contact, callback) – create a new contact and display in contactsUI.
  • openExistingContact (contact, callback) – where contact is an object with a valid recordID
  • updateContact (contact, callback) – where contact is an object with a valid recordID
  • deleteContact (contact, callback) – where contact is an object with a valid recordID
  • getContactsMatchingString (string, callback) – where string is any string to match a name (first, middle, family) to
  • getContactsByPhoneNumber (string, callback) – where string is a phone number to match to.
  • getContactsByEmailAddress (string, callback) – where string is an email address to match to.
  • checkPermission (callback) – checks permission to access Contacts ios only
  • requestPermission (callback) – request permission to access Contacts ios only
  • writePhotoToPath (callback) – 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((err, contacts) => {
  contacts.sort((a, b) => a.givenName.toLowerCase() > b.givenName.toLowerCase());
  console.log('contacts -> ', contacts);
  if (err === "denied") {
    alert("Permission to access contacts was denied");
    console.warn("Permission to access contacts was denied");
  } else {
    setContacts(contacts);
    console.log('contacts', contacts);
  }
});

I have used the getAll API which will provide all the contact list in 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 click of 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 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 in the callback as contacts. 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 form 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 init to make our React Native App. Assuming that you have node installed, you can use npm to install the react-native-cli command line utility. Open the terminal and go to the workspace and run

npm install -g react-native-cli

Run the following commands to create a new React Native project

react-native init ProjectName

If you want to start a new project with a specific React Native version, you can use the --version argument:

react-native init ProjectName --version X.XX.X
react-native init ProjectName --version react-native@next

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.

Installation of Pod

React Native 0.60 brings the auto-linking feature which links the library automatically and you just need to install the pod file using the following command

cd ios && pod install && cd ..

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 into 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"/>
PermissionPurpose
WRITE_CONTACTSTo Create Update the device’s Contact details
READ_CONTACTSTo 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 the 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 info tab which is info.plist

3. Click on the plus button to add a permission key “Privacy-Contact Usage Description” and value that will be visible when 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

/* This is an Access Contact List example from https://aboutreact.com/ */
/* 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((err, contacts) => {
      contacts.sort((a, b) => a.givenName.toLowerCase() > b.givenName.toLowerCase());
      console.log('contacts -> ', contacts);
      if (err === "denied") {
        alert("Permission to access contacts was denied");
        console.warn("Permission to access contacts was denied");
      } else {
        setContacts(contacts);
        console.log('contacts', contacts);
      }
    });
  }

  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, (err, contacts) => {
        contacts.sort((a, b) => a.givenName.toLowerCase() > b.givenName.toLowerCase());
        setContacts(contacts);
        console.log('contacts', contacts);
      });
    } else {
      Contacts.getContactsMatchingString(text, (err, 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

/* This is an Access Contact List example from https://aboutreact.com/ */
/* 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 => {
  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

/* This is an Access Contact List example from https://aboutreact.com/ */
/* 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) => {
  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>
    );
  };

  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
To run the project on an Android Virtual Device or on real debugging device
react-native run-android
or on the iOS Simulator by running
react-native run-ios (macOS only).

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 you 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. 🙂


Related Posts

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

      • Brother Thanks for reply …all time follow your Blog. By your Blog read I have all ready complete 2 apps which is live in App store and play store.

        Recently working on another But face some problem.
        In your post I sync my contact number Now I want to send multiple invitation in this number Just like what’s up Please help me

        Reply
  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

Leave a Comment

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