react-phone-input-2 icon indicating copy to clipboard operation
react-phone-input-2 copied to clipboard

Add method to update countryData from ref

Open gotexis opened this issue 4 years ago • 7 comments

Hi I went through the docs but didn't find an easy way. Is there a way to do this?

I would like to programmatically set country - when you click a button, set country to US / AU.

gotexis avatar May 25 '20 02:05 gotexis

@gotexis I just implemented something like this. My form has a country drop down and I wanted to set the country value on the phone input to whatever country the user chooses. I have a property in state for countryFormat, and I'm updating it in the onChange handler for the country dropdown. I have the phone input country prop value set to this.state.countryFormat. One gotcha I hit here was that you seem to have to omit the onlyCountries prop when you change the country value dynamically this way for some reason.

mimi26 avatar Jun 12 '20 20:06 mimi26

The input has a country prop. I guessing how this is not an easy way to change it :thinking:

bl00mber avatar Jun 13 '20 20:06 bl00mber

@bl00mber Is there a reason the onlyCountries prop won't dynamically update? I realized I can't use it if the input tries to guess other countries. I need both country and onlyCountries to update.

mimi26 avatar Jun 16 '20 20:06 mimi26

@mimi26 this functionality was never requested. Now when I look at the way how it may be implemented, I guess comparing these arrays which are passed to input may add excessive overload... I think I may want to add a method that should re-create country data when called from ref like phoneInputRef.current.recreateCountryData({onlyCountries... [optional parameters]})

(a note for me :laughing:)

bl00mber avatar Jun 16 '20 22:06 bl00mber

@bl00mber do you plan to add this functionality in the next release?

ionutmiftode avatar Jun 22 '20 15:06 ionutmiftode

Just adding in case someone else has the issue, I was able to force an update by adding a key prop to the phoneInput component. It was a suggestion from a very smart colleague.

mimi26 avatar Jun 24 '20 19:06 mimi26

@mimi26 Devilishly simple and effective, thanks for that idea 👍

apmeehan avatar Feb 01 '22 17:02 apmeehan