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
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
Share Improve this question edited May 22, 2019 at 4:36 Hamza Mazhar asked May 15, 2019 at 9:27 Hamza MazharHamza Mazhar 311 silver badge7 bronze badges4 Answers
Reset to default 6If you take a look at the docs here you'll see you can add a countries
prop to the ponent, 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.
We can use the prop countryPickerProps
<PhoneInput
countryPickerProps={{
countryCodes: ['IN', 'GB', 'US'],
}}
/>
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 pare it of your country list
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