React Native Phone Input with formatting and Hooks!
I recently decided to move away from react-native-phone-input
(Github link) because I just found it too annoying and it seemed like such an easy thing to remake with some Hooks. It was!
Although I don’t have the same features as the aforementioned library, it works well enough for me, and over time I can improve on it according to my needs.
I thought it might be a good idea to post it here in case anyone else would like to use it.
This was written for my app, that will be New Zealand based (when it’s launched) that’s why I added the NZ flag and hard coded the +64
country code.
I am also using formatNumber
from libphonenumber-js
library (Github link) to format the number AFTER the user enters their phone number.
Here’s a small gif of it working:
If you put the above in your components directory, you can include it:
Then within the screen that you want to display your phone input:
My onChangePgoneInput
is as simple as you thought:
Of course, to do what I’ve done (for confirming your mobile number), you just add another PhoneInput
component, but with a different onChange
.
There are quite a few things that is missing from this code, but the idea of me posting it was so you could have a “skeleton” so that you can then add your neccessary functionality to. An example here, would be to show a checkmark after entering the first one (if it’s a correct number from formatNumber
) and then if they enter the wrong number in the second input, you would show an
I do find quite often it’s far easier to make your own components rather than trying to hack existing ones to work how you want them to, and with React Hooks… it’s becoming far easier to take a bloated library from npm or GitHub and convert it into something tiny.
Have fun.