简体   繁体   中英

How to open default Contact app in react native using Expo?

How to open the default Contact app in react native using Expo?

my requirements are:

  1. Display a button to open the contact book on home screen.
  2. On clicking the button, open the list of contacts in user's phone.
  3. On contact list, each contact item should display the contact's profile picture, full name and the number/type of number(Home/work)
  4. Add a search bar that will allow the user to search contacts by name
  5. Once the user selects a contact, go back to home screen and display the chosen contact's phone number in a text field(not as an alert/toast).
  6. If a contact has multiple phone numbers, allow the user to pick only one phone number.
   import React, { useEffect, useState } from "react";       
   import {
StyleSheet,
View,
Text,
TextInput,
FlatList,
ActivityIndicator,
} from "react-native";
import * as Contacts from "expo-contacts";

export default function App() {
const [allcontacts, setcontact] = useState([]); //say set main state 
const [allcontactsfilter, setcontactfilter] = useState([]); // filter state
 const [searchcontact, setsearchcontact] = useState("");
const [loading, setloading] = useState(false);
 console.log(searchcontact);
 useEffect(() => {
   (async () => {
     const { status } = await Contacts.requestPermissionsAsync();
     if (status === "granted") {
       const { data } = await Contacts.getContactsAsync({
      fields: [
        Contacts.Fields.PhoneNumbers,
        //  Contacts.Fields.Emails
      ],
    });
    // console.log("collectio object", data);
    if (data.length > 0) {
      //   console.log("contact hellos", data);

      setcontact(data);

    setting same data in two-state help to manipulate state when we do filtering 
    process 

      setcontactfilter(data);
      setloading(false);
    }
  }
  })();
  setloading(true);
 }, []);

filter function

 const filtercontacts = (e) => {
const filtervalue = allcontactsfilter.filter((contact) => { <-- look here at 
   allcontactsfilter
  let lowercase = `${contact.firstName} ${contact.lastName}`.toLowerCase();
  let searchlowercase = e.toLowerCase();
  return lowercase.indexOf(searchlowercase) > -1;
});
setsearchcontact(setcontact(filtervalue)); 
};
  return (
 <View style={styles.container}>
  <TextInput
    style={{
      backgroundColor: "#D5D5D5",
      height: 40,
      width: "90%",
      borderBottomWidth: 0.3,
      borderBottomColor: "#ddd",
    }}
    placeholder="search"
    value={searchcontact}
    onChangeText={filtercontacts}
  />
  {loading ? (
    <View>
      <ActivityIndicator size={35} color="green" />
    </View>
  ) : null}

  <FlatList
    data={allcontacts}
    keyExtractor={(item, index) => index.toString()}
    renderItem={({ item }) => (
      <View style={{ minHeight: 70, padding: 5 }}>
        <Text>
          {/* {
            ("inside flatlist>>>,....",
            console.log(
              item.phoneNumbers == undefined || null
                ? []
                : item.phoneNumbers[0]?.number
            ))
          } */}
          {item?.firstName == null
            ? "please update name in your phone contact book"
            : item.firstName}
          {item?.lastName == null ? null : item.lastName}
        </Text>
        <Text style={{ color: "red" }}>
          {item.phoneNumbers == undefined || null
            ? []
            : item.phoneNumbers[0]?.number}
        </Text>
      </View>
    )}
    ListEmptyComponent={() => (
      <Text style={{ fontSize: 20, marginVertical: 40 }}>No contact </Text>
    )}
  />
  {/* {console.log("okstate..", allcontacts)} */}
   <Text>Contacts Module Example </Text>
   </View>
   );
  }

const styles = StyleSheet.create({
 container: {
  flex: 1,
  backgroundColor: "#fff",
alignItems: "center",
 justifyContent: "center",
},
});

apply style according to your need.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM