Accessing Device’s Contact List with React Native Contacts
Overview
Contacts are crucial in today's digital era, enabling communication and social connections. Smartphones now store contact information, replacing bulky phone directories. Each individual has a unique array of contacts, including phone numbers and email addresses.
In this article, we'll explore React Native Contacts, a powerful component for managing contacts in React Native applications. It enables effortless retrieval, modification, and addition of contacts.
Introduction to react-native-contacts
Contact management is important for a React Native application as it improves the user experience by providing seamless integration with the device's contact list. react-native-contacts allow the application to access the user's device contacts directly, eliminating the need for manual entry and reducing user effort. With react-native-contacts, the application can modify existing contacts or add new contacts directly to the device's contact list.
Installations
Install the react native contacts module using the below commands. For npm users:
For yarn users:
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): Promise - returns contact with defined contactId (or null if it doesn't exist)
-
getCount(): Promise - returns the number of contacts
-
getPhotoForId(contactId): Promise - returns a URI (or null) for a contacts photo
-
addContact(contact): Promise - adds a contact to the AddressBook.
-
openContactForm(contact) - create a new contact and display it in contactsUI.
-
openExistingContact(contact) - open existing contact (edit mode), where a contact is an object with a valid recordID
-
viewExistingContact(contact) - open existing contact (view mode), where a contact is an object with a valid recordID
-
editExistingContact(contact): Promise - add numbers to the contact, where a contact is an object with a valid recordID and an array of phoneNumbers
-
updateContact(contact): Promise - where a contact is an object with a valid recordID
-
deleteContact(contact) - where a contact is an object with a valid recordID
-
getContactsMatchingString(string): Promise<Contact[]> - where the string is any string to match a name (first, middle, family) to
-
getContactsByPhoneNumber(string): Promise<Contact[]> - where string is a phone number to match to.
-
getContactsByEmailAddress(string): Promise<Contact[]> - where string is an email address to match to.
-
checkPermission(): Promise - checks permission to access Contacts ios only
-
requestPermission(): Promise - request permission to access Contacts ios only
-
writePhotoToPath() - writes the contact photo to a given path Android only
Setting Up React Native Contacts
There isn’t much setup required for this module because autolinking handles most of the work. But for the permissions required for the contacts, we need to make slight additions after the linking. In the case of Android, autolinking handles all the work. The one thing we might need to check is the addition of the <uses-permission> tag for contacts in AndroidManifest.xml: Go to YourProject/android/app/src/main/ to edit the AndroidManifest.xml file.
To begin the iOS setup, the initial step involves the installation of pods in the iOS/ directory.
To proceed, the subsequent action involves incorporating a key into the info.plist file.
One can include a string of text to be displayed on the permission prompt specifically designed for iOS users.
Accessing Contacts in React Native Bare App
To access contacts details in React Native bare app we first need to import the react-native-contacts module in your React Native application:
Fetch All Contacts
In the above code snippet we are using the getAll() method to fetch all contacts. The method returns a promise that resolves to an array of contact objects. You can access the retrieved contacts in the then block and perform desired operations, such as logging them to the console. You can handle any errors that may occur using the catch block.
Get Specific Contacts
In the above code snippet we are using the getSpecificContact() method and provide the recordID of the contact you want to retrieve as an argument. The method returns a promise that resolves to the specified contact object. Access the retrieved contact in the then block and perform desired operations, such as logging it to the console.
Update a Contact
In the code above, contactId represents the unique ID of the contact to be updated. The updatedContact object contains the updated information for the contact, such as givenName, familyName, and phoneNumbers.
Accessing Contacts in React Native Expo App
The concept of fetching contacts in Expo is the same as above with a slight change in the received data structure.
Again, first we need to import the module:
To display the data in a list format, we will make use of the FlatList component. It should be noted that any listing component can be utilized for this purpose. The dummy component's files and structure remain unchanged, mirroring the original React Native example. Below is the sample code demonstrating the implementation of the list. Paste the below code in ContactsList.js:
In the above code, the ContactsList component is defined as a functional component. It initializes a state variable contacts using the useState hook, which will store the contact data. The useEffect hook is used to perform an asynchronous operation when the component mounts. Inside the useEffect hook, an immediately invoked asynchronous function is defined.
Within this function, the requestPermissionsAsync method from expo-contacts is called to request the necessary permission to access the user's contacts. If the permission is granted (status === "granted"), the getContactsAsync method is called to retrieve the contact data. The fields parameter is set to retrieve only the phone numbers of the contacts. If the data array returned is not empty (data.length > 0), it is stored in the contacts state variable using the setContacts function, and the first contact is logged to the console for verification.
The keyExtractor function is defined to provide a unique key for each item in the contact list. It checks if the item.id exists and returns it as a string, or if it doesn't exist, it uses the index (idx) of the item in the array.
The renderItem function is defined to render each item in the contact list. It takes the item and index as parameters and renders the Contact component, passing the item as a prop.
Paste the below code in the Contact.js file:-
Inside the component's render function, a layout structure is defined using nested View components. The outermost View component has the styles.contactCon style applied to it. It sets the flex to 1, meaning it will expand to fill the available space horizontally. It also applies padding, a bottom border width of 0.5, and a bottom border color of #d9d9d9. Inside the imgCon View, there is another nested View called placeholder. It is used to display the contact's initials or a placeholder image. It has a fixed width and height of 55, with a borderRadius of 30 to make it circular. The overflow property is set to "hidden" to ensure that the content doesn't overflow beyond the circular shape.
Finally paste the below code in index.js:-
FAQs
Q. What are the main features of React Native Contacts?
A. React Native Contacts offers various features for managing contact data. Some of the main features include:
Retrieving all contacts or specific contacts based on filters.
Adding new contacts to the device's contact list.
Updating existing contacts with new information.
Deleting contacts from the device's contact list.
Searching for contacts by name or other attributes.
Handling permissions to access and manage contacts.
Supporting multiple platforms (iOS and Android).
Q. How can I retrieve all contacts using React Native Contacts?
A. To retrieve all contacts using React Native Contacts, you can utilize the getContacts or getAll methods provided by the library. These methods return a promise that resolves to an array of contact objects containing the contact information, such as names, phone numbers, email addresses, and more.
Q. Are there any alternatives to React Native Contacts?
A. Yes, there are other contact management libraries available for React Native, such as react-native-contacts-wrapper and react-native-addressbook. These libraries offer similar functionality for working with contacts, so you can choose the one that best fits your project requirements and preferences.
Conclusion
In conclusion,
- React Native Contacts simplifies management and interaction with native contacts in React Native applications.
- It offers comprehensive APIs for retrieving, modifying, adding, and deleting contacts, as well as operations like searching, filtering, and sorting.
- Integration of React Native Contacts provides seamless access to device contacts for efficient contact management.
- The article provided a step-by-step guide for setting up React Native Contacts, including installations and permissions for Android and iOS.
- It demonstrated accessing and displaying contact details using the getAll function and FlatList component.
- The Contact component showcased presenting contact information in a customizable list format.