react-native-country-picker-modal

repository·master·Indexed 22 days ago

https://github.com/xcarpentier/react-native-country-picker-modal

A React Native component for selecting countries via a modal interface. It features searching, filtering, and support for flags, emojis, calling codes, and currencies. The library includes customizable components such as CountryPicker, CountryList, and CountryFilter, and supports a dark theme via DARK_THEME. Version 2.0.0.

Tokens
8.5K
Snippets
30
Records
35
Agent score
70%

What's inside react-native-country-picker-modal

  1. Basic Usage of CountryPicker

    master

    To use the CountryPicker component, import it from react-native-country-picker-modal. You typically manage the selected countryCode and the full country object in your component state. Use the onSelect callback to update your state when a user picks a country.

    import React, { useState } from 'react'
    import { View, Text, StyleSheet } from 'react-native'
    import CountryPicker from 'react-native-country-picker-modal'
    import { CountryCode, Country } from './src/types'
    
    export default function App() {
      const [countryCode, setCountryCode] = useState<CountryCode>('FR')
      const [country, setCountry] = useState<Country>(null)
    
      const onSelect = (country: Country) => {
        setCountryCode(country.cca2)
        setCountry(country)
      }
    
      return (
        <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
          <CountryPicker
            countryCode={countryCode}
            withFilter
            withFlag
            withCountryNameButton
            withAlphaFilter
            withCallingCode
            withEmoji
            onSelect={onSelect}
            visible
          />
          {country !== null && (
            <Text>{JSON.stringify(country, null, 2)}</Text>
          )}
        </View>
      )
    }
  2. Configure the Country Picker theme

    master

    The react-native-country-picker-modal library provides a theming system to customize the appearance of the picker. You can use the predefined DEFAULT_THEME or DARK_THEME, or provide a custom theme object that implements the Theme type. The Theme type is a partial implementation of the default theme properties.

    Available theme properties include:

    • primaryColor: The main color of the picker components.
    • primaryColorVariant: A variant color for primary elements.
    • backgroundColor: The background color of the modal/list.
    • onBackgroundTextColor: The color of text displayed on the background.
    • fontSize: The font size for text elements.
    • fontFamily: The font family (defaults to System on iOS, Roboto on Android, and Arial on Web).
    • filterPlaceholderTextColor: The color of the placeholder text in the search filter.
    • activeOpacity: The opacity level when an item is pressed.
    • itemHeight: The height of list items.
    • flagSize: The size of the flags in the list (defaults to 20 on Android, 30 otherwise).
    • flagSizeButton: The size of the flag in the selection button (defaults to 20 on Android, 30 otherwise).
    import { Theme } from 'react-native-country-picker-modal';
    
    const myCustomTheme: Theme = {
      primaryColor: '#ff0000',
      backgroundColor: '#f0f0f0',
      fontSize: 18
    };
  3. Configure CountryPicker props

    master

    The CountryPicker component accepts several props to customize its behavior and appearance:

    Selection & Data

    • countryCode: The currently selected CountryCode.
    • onSelect: Callback function (country: Country) => void triggered when a country is selected.
    • preferredCountries: An array of CountryCode that appear first in the list (requires withAlphaFilter to be false).
    • region?: Filter by Region.
    • subregion?: Filter by Subregion.
    • countryCodes?: An array of CountryCode to limit the list.

    UI Customization

    • visible: Boolean to control visibility.
    • withFlag: Show flags in the list.
    • withEmoji: Show emoji flags.
    • withFilter: Enable the search filter.
    • withAlphaFilter: Enable alphabetical filtering.
    • withCallingCode: Show calling codes.
    • withCurrency: Show currency information.
    • withCountryNameButton: Show the country name on the trigger button.
    • withCurrencyButton: Show the currency on the trigger button.
    • withCallingCodeButton: Show the calling code on the trigger button.
    • withFlagButton: Show the flag on the trigger button.
    • withCloseButton: Show a close button in the modal.
    • theme: Apply a specific Theme (e.g., DARK_THEME).
    • translation: Set the TranslationLanguageCode.

    Component Overrides & Styling

    • renderFlagButton: Custom renderer for the flag button.
    • renderCountryFilter: Custom renderer for the country filter (accepts TextInputProps).
    • containerButtonStyle: StyleProp<ViewStyle> for the button container.
    • closeButtonStyle: StyleProp<ViewStyle> for the close button.
    • closeButtonImageStyle: StyleProp<ImageStyle> for the close button image.
    • closeButtonImage: ImageSourcePropType for the close button icon.
    • modalProps: Props passed to the underlying React Native Modal.
    • filterProps: Props passed to the country filter (CountryFilterProps).
    • flatListProps: Props passed to the underlying FlatList (FlatListProps<Country>).

    Lifecycle & Native

    • onOpen: Callback when the modal opens.
    • onClose: Callback when the modal closes.
    • disableNativeModal: Boolean. If true, you must wrap your entire app with CountryModalProvider.
  4. Use the default CountryPicker component

    master

    The default export of this package is the Main component (often used as CountryPicker), which provides a complete country selection interface. It is wrapped in ThemeProvider and CountryProvider to handle styling and translations.

    To use it, you must provide a countryCode and an onSelect callback. You can customize the appearance using various boolean props (e.g., withEmoji, withCallingCode) and styling props like containerButtonStyle.

    import CountryPicker from 'react-native-country-picker-modal';
    
    // ... inside your component
    <CountryPicker
      countryCode="US"
      onSelect={(country) => console.log(country)}
      withFlag={true}
      withCallingCode={true}
    />
  5. Generate alphabet index with getLetters

    master

    Given an array of Country objects, getLetters returns a sorted array of unique uppercase characters representing the first letter of each country's name. This is useful for building alphabetical jump-lists in UI components.

    import { getLetters } from 'react-native-country-picker-modal';
    
    const letters = getLetters(countries);
    // Example output: ['A', 'B', 'C', ...]
  6. Use the CountryFilter component

    master

    The CountryFilter component is a specialized TextInput used to filter the country list within the picker. It is pre-configured with specific styling (height, width) and theme-aware properties like placeholderTextColor and color derived from the internal useTheme hook.

    Since it extends TextInputProps, you can pass any standard React Native TextInput props to it (e.g., onChangeText, value, keyboardType).

    Default Props:

    • autoFocus: false
    • placeholder: 'Enter country name'
    import { CountryFilter } from 'react-native-country-picker-modal';
    
    // Example usage within a component
    <CountryFilter 
      placeholder="Search for a country..." 
      onChangeText={(text) => console.log(text)} 
    />
  7. Get detailed country information with getCountryInfoAsync

    master

    Retrieve a combined object containing the country's name, currency, and calling code for a specific country code.

    Parameters:

    • countryCode: The CountryCode to look up.
    • translation: (Optional) The TranslationLanguageCode for the name.
    import { getCountryInfoAsync } from 'react-native-country-picker-modal';
    
    const info = await getCountryInfoAsync({
      countryCode: 'US',
      translation: 'en'
    });
    // Returns: { countryName: 'United States', currency: 'USD', callingCode: '1' }
  8. Customize the Flag Button and Country Filter

    master

    You can replace the default UI components for the flag button and the search filter using the renderFlagButton and renderCountryFilter props.

    • renderFlagButton: Receives props compatible with FlagButton (like countryCode, onOpen, containerButtonStyle, etc.).
    • renderCountryFilter: Receives props compatible with CountryFilter (like onChangeText, value, onFocus, etc.).
    <CountryPicker
      renderFlagButton={(props) => (
        <MyCustomButton 
          onPress={props.onOpen} 
          label={props.countryCode} 
        />
      )}
      renderCountryFilter={(props) => (
        <MyCustomSearchInput 
          value={props.value} 
          onChangeText={props.onChangeText} 
        />
      )}
      onSelect={(country) => console.log(country)}
    />
  9. Use the CountryList component

    master

    The CountryList component renders a scrollable list of countries. It supports filtering, alphabetical navigation (via an alpha filter), and customizable display options for flags, emojis, calling codes, and currencies. It uses a FlatList internally, so you can pass standard FlatListProps to customize its behavior.

    import { CountryList } from 'react-native-country-picker-modal';
    
    // Assuming 'countries' is an array of Country objects
    <CountryList
      data={countries}
      onSelect={(country) => console.log(country)}
      withFlag={true}
      withEmoji={true}
      withCallingCode={true}
      withCurrency={true}
      withAlphaFilter={true}
      filter="United"
    />