Reading contacts in react-native

Apps like whatsapp, hike or any other messaging app required you to access the contacts inside the app. This is the basic step to develop one such app.

Let’s learn how we can achieve this inside react -native.

We are going to use the npm package react-native-contacts

Versions used –

"react": "16.8.6",
"react-native": "0.60.5",
"react-native-contacts": "^5.0.2"

Setup

Add the npm package as

npm i react-native-contacts --save

Android

In android/settings.gradle

include ':react-native-contacts'

project(':react-native-contacts').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-contacts/android')

In android/app/build.gradle

...
dependencies {
    ...
    implementation project(':react-native-contacts')

As we are using react-native 0.60, we don’t need to link this package manually. It will be linked already.

IOS

  1. open in xcode open ios/yourProject.xcodeproj/
  2. drag ./node_modules/react-native-contacts/ios/RCTContacts.xcodeproj to Libraries in you project view.
  3. In the XCode project navigator, select your project, select the Build Phases tab drag Libraries > RCTContacts.xcodeproj > Products > libRCTContacts.a into the Link Binary With Libraries section. Video to clarifyAdding Camera Roll to an ios project in React Native.
  4. Add kit specific “permission” keys to your Xcode Info.plist file, in order to make requestPermission work. Otherwise your app crashes when requesting the specific permission. Open Info.plist. Add key Privacy - Contacts Usage Description with your kit specific permission. The value for the key is optional in development. If you submit to the App Store the value must explain why you need this permission.

Permissions

To read contacts, in Android API 23+,

We don’t require to add READ_CONTACTS permission, that is already added automatically to AndroidManifest.xml. We just need to request it from the code. If in case, WRITE_CONTACTS permission is required. Just add it into AndroidManifest.xml

 <uses-permission android:name="android.permission.WRITE_CONTACTS" /> 

API 22 and below

Add READ_PROFILE and/or WRITE_PROFILE permissions to AndroidManifest.xml

...
<uses-permission android:name="android.permission.READ_PROFILE" />
...

Code

If the platform is android we are requiring the permission from the user when the component is loaded. If ios, we are fetching the contacts directly.

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 *
 * @format
 * @flow
 */

import React from 'react';
import {
    StyleSheet,
    FlatList,
    View,
    Text,
    Platform,
    PermissionsAndroid,
} from 'react-native';


import Contacts from 'react-native-contacts';

const styles = StyleSheet.create({
    itemContainer: {
        margin: 10
    },
    contactName: {
        fontSize:16,
        color: 'blue'
    }
})

class ContactList extends React.Component {

    constructor(props) {
        super(props)
        this.state = {
            contacts: null
        }
    }

    componentDidMount() {
        if (Platform.OS === 'android') {
            PermissionsAndroid.request(
                PermissionsAndroid.PERMISSIONS.READ_CONTACTS,
                {
                    title: 'Contacts',
                    message: ' This app would like to see your contacts'
                }
            ).then(() => {
                this.getList();
            })
        } else if(Platform.OS === 'ios') {
            this.getList();
        }
    }

    getList = () => {
        Contacts.getAll((err, contacts) => {
            if (err === 'denied') {
                console.log("cannot access");
            } else {
                this.setState({ contacts });
                console.log(contacts);
            }
        })
    }

    renderItem = ({item}) => (
        <View style={styles.itemContainer}>
            <Text style={styles.contactName}>
                Name: {`${item.givenName} `} {item.familyName}
            </Text>
            {item.phoneNumbers.map(phone => (
                <Text style={styles.phones}>{phone.label} : {phone.number}</Text>
            ))}
        </View>
    )
    render() {
        return (
            <View style={styles.container}>
                <FlatList
                    data={this.state.contacts}
                    renderItem={this.renderItem}
                    //Setting the number of column
                    numColumns={1}
                    keyExtractor={(item, index) => index}
                />
            </View>
        )
    }
}



export default ContactList;

Hope you enjoyed this post and it helped you to understand how react-native-contact works.

If you are curious about javascript, react and react-native, Here are some more blogs for you 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *