Hamza Mazhar
Hamza Mazhar

Reputation: 31

How to limited the countries list in npm react-phone-number-input package

when react-phone-number-input use this npm package i want to allow limited countries show in dropdown if user enter other country which is not in list it display error not allow this country there is no prop where i limit the countries

Upvotes: 3

Views: 4647

Answers (4)

Harshal
Harshal

Reputation: 8310

We can use the prop countryPickerProps

<PhoneInput
  countryPickerProps={{
    countryCodes: ['IN', 'GB', 'US'],
  }}
/>

Upvotes: 1

just-be-weird
just-be-weird

Reputation: 1310

To achieve this first create list of countries that you want to show in dropdown. Then on Blur run the validation if you want.

const whitelisted_conutries = ['WS',  'SB',  'TK',  'TO',  'TV',  'VU',  'WF',  'HK']:

then pass this to countries prop of PhoneInput like so,

import { isValidPhoneNumber } from 'react-phone-number-input';

      <PhoneInput
       defaultCountry="GB"
       flagUrl={'https://flag.pk/flags/4x3/{xx}.svg'}
       countries={whitelist}
       value={phone}
       onChange={(phone) => setState({ phone })}
       onBlur={() =>
       setState({
              hasEnterPhone: true,
              error: {
                ...error,
                phone: !phone
                  ? ''
                  : !isValidPhoneNo(phone) &&
                    'Please enter a valid mobile phone number.',
              },
            })
          }
        />

For more info on supported props refer developers docs tagged by @jamie in thread: Docs

Upvotes: 0

Hamza Mazhar
Hamza Mazhar

Reputation: 31

Build a custom array of countries and then use the parseNumber function from libphonenumber-js library and get the country code from the user input number and compare it of your country list

Upvotes: 0

Jamie - Decodefy Ltd
Jamie - Decodefy Ltd

Reputation: 1397

If you take a look at the docs here you'll see you can add a countries prop to the component, and provide it with an array of strings. Their example shows this array:

["RU", "UA", "KZ"]

This would limit the list of countries to just those 3.

Upvotes: 6

Related Questions