HomeGuidesReferenceLearn

Expo Contacts

GitHub

npm


expo-contacts provides access to the device's system contacts, allowing you to get contact information as well as adding, editing, or removing contacts.

Platform Compatibility

Android DeviceAndroid EmulatoriOS DeviceiOS SimulatorWeb

Installation

Terminal
npx expo install expo-contacts

If you're installing this in a bare React Native app, you should also follow these additional installation instructions.

Usage

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

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

        if (data.length > 0) {
          const contact = data[0];
          console.log(contact);
        }
      }
    })();
  }, []);

  return (
    <View style={styles.container}>
      <Text>Contacts Module Example</Text>
    </View>
  );
}

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

API

import * as Contacts from 'expo-contacts';

Methods

Contacts.isAvailableAsync()

Returns whether the Contacts API is enabled on the current device. This does not check the app permissions.

Returns

Async boolean, indicating whether the Contacts API is available on the current device. Currently this resolves to true on iOS and Android only.

Contacts.requestPermissionsAsync()

Asks the user to grant permissions for accessing contacts data.

Returns

A promise that resolves to an object of type PermissionResponse.

Contacts.getPermissionsAsync()

Checks user's permissions for accessing contacts data.

Returns

A promise that resolves to an object of type PermissionResponse.

Contacts.getContactsAsync(contactQuery)

Contacts.getContactsAsync(contactQuery: ContactQuery): Promise<ContactResponse>

Return a list of contacts that fit a given criteria. You can get all of the contacts by passing no criteria.

Parameters

NameTypeDescription
contactQueryContactQueryUsed to query contacts.

Returns

NameTypeDescription
contactResponseContactResponseContacts returned from the query.

Example

const { data } = await Contacts.getContactsAsync({
  fields: [Contacts.Fields.Emails],
});

if (data.length > 0) {
  const contact = data[0];
  console.log(contact);
}

Contacts.getContactByIdAsync(contactId, fields)

Contacts.getContactByIdAsync(contactId: string, fields: FieldType[]): Promise<Contact>

Returns a contact matching the input id. Used for gathering precise data about a contact.

Parameters

NameTypeDescription
contactIdstringThe ID of a system contact.
fieldsFieldType[]If available the fields defined will be returned. If nil then all fields will be returned.

Returns

NameTypeDescription
contactContactContact with an ID matching the input ID.

Example

const contact = await Contacts.getContactByIdAsync('161A368D-D614-4A15-8DC6-665FDBCFAE55');
if (contact) {
  console.log(contact);
}

Contacts.addContactAsync(contact, containerId)

Contacts.addContactAsync(contact: Contact, containerId: string): Promise<string>

Creates a new contact and adds it to the system.

Note: For Android users, the Expo Go app does not have the required WRITE_CONTACTS permission to write to Contacts. In order to do this, you must build a standalone app and add permission through there.

Parameters

NameTypeDescription
contactContactA contact with the changes you wish to persist. The id parameter will not be used.
containerIdstringIOS ONLY: The container that will parent the contact

Returns

NameTypeDescription
contactIdstringID of the new system contact.

Example

const contact = {
  [Contacts.Fields.FirstName]: 'Bird',
  [Contacts.Fields.LastName]: 'Man',
  [Contacts.Fields.Company]: 'Young Money',
};
const contactId = await Contacts.addContactAsync(contact);

Contacts.updateContactAsync(contact)

iOS Only - temporary

Contacts.updateContactAsync(contact: Contact): Promise<string>

Mutate the information of an existing contact.

On Android, you can use presentFormAsync to make edits to contacts. Due to an iOS bug, nonGregorianBirthday cannot be modified.

Contacts.presentFormAsync(contactId, contact, formOptions)

Contacts.presentFormAsync(contactId: string, contact: Contact, formOptions: FormOptions): Promise<any>

Present a native form for manipulating contacts

Parameters

NameTypeDescription
contactIdstringThe ID of a system contact.
contactContactA contact with the changes you wish to persist.
formOptionsFormOptionsOptions for the native editor

Example

// Edit contact
await Contacts.presentFormAsync('161A368D-D614-4A15-8DC6-665FDBCFAE55');

Parameters

NameTypeDescription
contactContactA contact with the changes you wish to persist. The contact must contain a valid id

Returns

NameTypeDescription
contactIdstringThe ID of a system contact.

Example

const contact = {
  id: '161A368D-D614-4A15-8DC6-665FDBCFAE55',
  [Contacts.Fields.FirstName]: 'Drake',
  [Contacts.Fields.Company]: 'Young Money',
};
await Contacts.updateContactAsync(contact);

Contacts.removeContactAsync(contactId)

iOS Only - temporary

Contacts.removeContactAsync(contactId: string): Promise<any>

Delete a contact from the system.

Parameters

NameTypeDescription
contactIdstringID of the contact you want to delete.

Example

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

Contacts.writeContactToFileAsync(contactQuery)

Contacts.writeContactToFileAsync(contactQuery: ContactQuery): Promise<string>

Query a set of contacts and write them to a local uri that can be used for sharing with ReactNative.Share.

Parameters

NameTypeDescription
contactQueryContactQueryUsed to query contacts you want to write.

Returns

NameTypeDescription
localUristringShareable local uri

Example

const localUri = await Contacts.writeContactToFileAsync({
  id: '161A368D-D614-4A15-8DC6-665FDBCFAE55',
});
Share.share({ url: localUri, message: 'Call me!' });

IOS-Only Methods

iOS contacts have a multi-layered grouping system that you can access through this API.

Contacts.addExistingGroupToContainerAsync(groupId, containerId)

Contacts.addExistingGroupToContainerAsync(groupId: string, containerId: string): Promise<any>

Add a group to a container.

Parameters

NameTypeDescription
groupIdstringThe group you wish to target.
containerIdstringThe container you to add membership to.

Example

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

Contacts.createGroupAsync(groupName, containerId?)

Contacts.createGroupAsync(groupName: string, containerId?: string): Promise<string>

Create a group with a name, and add it to a container. If the container is undefined, the default container will be targeted.

Parameters

NameTypeDescription
namestringName of the new group.
containerIdstringThe container you to add membership to.

Returns

NameTypeDescription
groupIdstringID of the new group.

Example

const groupId = await Contacts.createGroupAsync('Sailor Moon');

Contacts.updateGroupNameAsync(groupName, groupId)

Contacts.updateGroupNameAsync(groupName: string, groupId: string): Promise<any>

Change the name of an existing group.

Parameters

NameTypeDescription
groupNamestringNew name for an existing group.
groupIdstringID for the group you want to edit.

Example

await Contacts.updateGroupName('Sailor Moon', '161A368D-D614-4A15-8DC6-665FDBCFAE55');

Contacts.removeGroupAsync(groupId)

Contacts.removeGroupAsync(groupId: string): Promise<any>

Delete a group from the device.

Parameters

NameTypeDescription
groupIdstringID of the group.

Example

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

Contacts.addExistingContactToGroupAsync(contactId, groupId)

Contacts.addExistingContactToGroupAsync(contactId: string, groupId: string): Promise<any>

Add a contact as a member to a group. A contact can be a member of multiple groups.

Parameters

NameTypeDescription
contactIdstringID of the contact you want to edit.
groupIdstringID for the group you want to add membership to.

Example

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

Contacts.removeContactFromGroupAsync(contactId, groupId)

Contacts.removeContactFromGroupAsync(contactId: string, groupId: string): Promise<any>

Remove a contact's membership from a given group. This will not delete the contact.

Parameters

NameTypeDescription
contactIdstringID of the contact you want to remove.
groupIdstringID for the group you want to remove membership of.

Example

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

Contacts.getGroupsAsync(query)

Contacts.getGroupsAsync(query: GroupQuery): Promise<Group[]>

Query and return a list of system groups.

Parameters

NameTypeDescription
queryGroupQueryInformation regarding which groups you want to get.

Returns

NameTypeDescription
groupsGroup[]Collection of groups that fit query.

Example

const groups = await Contacts.getGroupsAsync({ groupName: 'sailor moon' });
const allGroups = await Contacts.getGroupsAsync({});

Contacts.getDefaultContainerIdAsync()

Contacts.getDefaultContainerIdAsync(): Promise<string>

Get the default container's ID.

Returns

NameTypeDescription
containerIdstringDefault container ID.

Example

const containerId = await Contacts.getDefaultContainerIdAsync();

Contacts.getContainersAsync(containerQuery)

Contacts.getContainersAsync(containerQuery: ContainerQuery): Promise<Container[]>

Query a list of system containers.

Parameters

NameTypeDescription
containerQueryContainerQueryInformation used to gather containers.

Returns

NameTypeDescription
containerIdstringCollection of containers that fit query.

Example

const allContainers = await Contacts.getContainersAsync({
  contactId: '665FDBCFAE55-D614-4A15-8DC6-161A368D',
});

Types

Contact

A set of fields that define information about a single entity.

NameTypeDescriptioniOSAndroid
idstringImmutable identifier used for querying and indexing.
namestringFull name with proper format.
firstNamestringGiven name.
middleNamestringMiddle name.
lastNamestringFamily name.
maidenNamestringMaiden name.
namePrefixstringDr. Mr. Mrs. Ect...
nameSuffixstringJr. Sr. Ect...
nicknamestringAn alias to the proper name.
phoneticFirstNamestringPronunciation of the first name.
phoneticMiddleNamestringPronunciation of the middle name.
phoneticLastNamestringPronunciation of the last name.
companystringOrganization the entity belongs to.
jobTitlestringJob description.
departmentstringJob department.
notestringAdditional information.✅*
imageAvailablebooleanUsed for efficient retrieval of images.
imageImageThumbnail image (ios: 320x320)
rawImageImageRaw image without cropping, usually large.
contactTypeContactTypeDenoting a person or company.
birthdayDateBirthday information in Gregorian format.
datesDate[]A labeled list of other relevant user dates in Gregorian format.
relationshipsRelationship[]Names of other relevant user connections
emailsEmail[]Email addresses
phoneNumbersPhoneNumber[]Phone numbers
addressesAddress[]Locations
instantMessageAddressesInstantMessageAddress[]IM connections
urlAddressesUrlAddress[]Web Urls
nonGregorianBirthdayDateBirthday that doesn't conform to the Gregorian calendar format, interpreted based on the CalendarFormat setting.
socialProfilesSocialProfile[]Social networks
thumbnailImageDeprecated: Use image
previousLastNamestringDeprecated: Use maidenName

*On iOS 13 and up, the note field requires your app to request additional entitlements. The Expo Go app does not contain those entitlements, so in order to test this feature you will need to request the entitlement from Apple here, set the ios.accessesContactNotes field in app.json to true, and build your app as a standalone app.

Group

iOS Only

A parent to contacts. A contact can belong to multiple groups. To get a group's children you can query with getContactsAsync({ groupId })

Here are some different query operations:

  • Child Contacts: getContactsAsync({ groupId })
  • Groups From Container: getGroupsAsync({ containerId })
  • Groups Named: getContainersAsync({ groupName })
NameTypeDescription
idstringImmutable id representing the group
namestringThe editable name of a group

Container

iOS Only

A parent to contacts and groups. You can query the default container with getDefaultContainerIdAsync(). Here are some different query operations:

  • Child Contacts: getContactsAsync({ containerId })
  • Child Groups: getGroupsAsync({ containerId })
  • Container from Contact: getContainersAsync({ contactId })
  • Container from Group: getContainersAsync({ groupId })
  • Container from ID: getContainersAsync({ containerId })
NameTypeDescription
idstringImmutable id representing the group
namestringThe editable name of a group

Date

NameTypeDescription
daynumberDay.
monthnumberMonth - adjusted for JS Date which starts at 0.
yearnumberYear.
formatCalendarFormatTypeFormat for input date.
idstringUnique ID.
labelstringLocalized display name.

Relationship

NameTypeDescription
namestringName of related contact.
idstringUnique ID.
labelstringLocalized display name.

Email

NameTypeDescription
emailstringemail address.
isPrimarybooleanPrimary email address.
idstringUnique ID.
labelstringLocalized display name.

PhoneNumber

NameTypeDescription
numberstringPhone number.
isPrimarybooleanPrimary phone number.
digitsstringPhone number without format, ex: 8674305.
countryCodestringCountry code, ex: +1.
idstringUnique ID.
labelstringLocalized display name.

Address

NameTypeDescription
streetstringStreet name.
citystringCity name.
countrystringCountry name.
regionstringRegion or state name.
neighborhoodstringNeighborhood name.
postalCodestringLocal post code.
poBoxstringP.O. Box.
isoCountryCodestringStandard code.
idstringUnique ID.
labelstringLocalized display name.

SocialProfile

iOS Only

NameTypeDescription
servicestringName of social app.
usernamestringUsername in social app.
localizedProfilestringLocalized name.
urlstringWeb URL.
userIdstringUID for social app.
idstringUnique ID.
labelstringLocalized display name.

InstantMessageAddress

NameTypeDescription
servicestringName of social app.
usernamestringUsername in IM app.
localizedServicestringLocalized name of app.
idstringUnique ID.
labelstringLocalized display name.

UrlAddress

NameTypeDescription
urlstringWeb URL
idstringUnique ID.
labelstringLocalized display name.

Image

Information regarding thumbnail images.

NameTypeiOSAndroid
uristring
widthnumber
heightnumber
base64string

Android: You can get dimensions using ReactNative.Image.getSize. Avoid using Base 64 in React Native

FormOptions

Denotes the functionality of a native contact form.

NameTypeDescription
displayedPropertyKeysFieldType[]The properties that will be displayed. iOS: Does nothing in editing mode.
messagestringController title.
alternateNamestringUsed if contact doesn't have a name defined.
cancelButtonTitlestringThe name of the left bar button.
groupIdstringThe parent group for a new contact.
allowsEditingbooleanAllows for contact mutation.
allowsActionsbooleanActions like share, add, create.
shouldShowLinkedContactsbooleanShows similar contacts.
isNewbooleanPresent the new contact controller - if false the unknown controller will be shown.
preventAnimationbooleanPrevents the controller from animating in.

ContactQuery

Used to query contacts from the user's device.

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.

GroupQuery

iOS Only

Used to query native contact groups.

NameTypeDescription
groupNamestringQuery all groups matching a name.
groupIdstringQuery the group with a matching ID.
containerIdstringQuery all groups that belong to a certain container.

ContainerQuery

iOS Only

Used to query native contact containers.

NameTypeDescription
contactIdstringQuery all the containers that parent a contact.
groupIdstringQuery all the containers that parent a group.
containerIdstringQuery a container from it's ID.

ContactResponse

The return value for queried contact operations like getContactsAsync.

NameTypeDescription
dataContact[]An array of contacts that match a particular query.
hasNextPagebooleanThis will be true if there are more contacts to retrieve beyond what is returned.
hasPreviousPagebooleantrue if there are previous contacts that weren't retrieved due to pageOffset.
totalnumberDeprecated: use data.length to get the number of contacts returned.

Constants

Field

const contactField = Contact.Fields.FirstName;
NameValueiOSAndroid
ID'id'
Name'name'
FirstName'firstName'
MiddleName'middleName'
LastName'lastName'
NamePrefix'namePrefix'
NameSuffix'nameSuffix'
PhoneticFirstName'phoneticFirstName'
PhoneticMiddleName'phoneticMiddleName'
PhoneticLastName'phoneticLastName'
Birthday'birthday'
Emails'emails'
PhoneNumbers'phoneNumbers'
Addresses'addresses'
InstantMessageAddresses'instantMessageAddresses'
UrlAddresses'urlAddresses'
Company'company'
JobTitle'jobTitle'
Department'department'
ImageAvailable'imageAvailable'
Image'image'
Note'note'
Dates'dates'
Relationships'relationships'
Nickname'nickname'
RawImage'rawImage'
MaidenName'maidenName'
ContactType'contactType'
SocialProfiles'socialProfiles'
NonGregorianBirthday'nonGregorianBirthday'
ThumbnailDeprecated: use Image
PreviousLastNameDeprecated: use MaidenName

FormType

const formType = Contacts.FormTypes.New;
NameValueDescription
New'new'Creating a contact
Unknown'unknown'Displaying a contact with actions
Default'default'Information regarding a contact

ContactType

iOS Only

const contactType = Contacts.ContactTypes.Person;
NameValueDescription
Person'person'Contact is a human
Company'company'Contact is group or company

SortType

const sortType = Contacts.SortTypes.FirstName;
NameValueDescriptioniOSAndroid
FirstName'firstName'Sort by first name in ascending order
LastName'lastName'Sort by last name in ascending order
UserDefault'userDefault'The user default method of sorting

ContainerType

iOS Only

const containerType = Contacts.ContainerTypes.CardDAV;
NameValueDescription
Local'local'A local non-iCloud container
Exchange'exchange'In association with Email
CardDAV'cardDAV'cardDAV protocol used for sharing
Unassigned'unassigned'Unknown

CalendarFormat

const calendarFormat = Contacts.CalendarFormats.Coptic;

This format denotes the common calendar format used to specify how a date is calculated in nonGregorianBirthday fields.

ConstantvalueiOSAndroid
Gregorian'gregorian'
Buddhist'buddhist'
Chinese'chinese'
Coptic'coptic'
EthiopicAmeteMihret'ethiopicAmeteMihret'
EthiopicAmeteAlem'ethiopicAmeteAlem'
Hebrew'hebrew'
ISO8601'iso8601'
Indian'indian'
Islamic'islamic'
IslamicCivil'islamicCivil'
Japanese'japanese'
Persian'persian'
RepublicOfChina'republicOfChina'
IslamicTabular'islamicTabular'
IslamicUmmAlQura'islamicUmmAlQura'

Contact Fields

Deprecated: Use Contacts.Fields

This table illustrates what fields will be added on demand to every contact.

ConstantvalueiOSAndroid
PHONE_NUMBERS'phoneNumbers'
EMAILS'emails'
ADDRESSES'addresses'
IMAGE'image'
NOTE'note'
NAME_PREFIX'namePrefix'
NAME_SUFFIX'nameSuffix'
PHONETIC_FIRST_NAME'phoneticFirstName'
PHONETIC_MIDDLE_NAME'phoneticMiddleName'
PHONETIC_LAST_NAME'phoneticLastName'
IM_ADDRESSES'instantMessageAddresses'
URLS'urlAddresses'
DATES'dates'
NON_GREGORIAN_BIRTHDAY'nonGregorianBirthday'
SOCIAL_PROFILES'socialProfiles'
RAW_IMAGE'rawImage'
THUMBNAIL'thumbnail'DeprecatedDeprecated
PREVIOUS_LAST_NAME'previousLastName'DeprecatedDeprecated

Was this doc helpful?