catamphetamine / react-phone-number-input

React component for international phone number input
http://catamphetamine.gitlab.io/react-phone-number-input/
MIT License
914 stars 194 forks source link

Allow defaultCountry to be extracted from initial value #378

Closed andregoldstein closed 3 years ago

andregoldstein commented 3 years ago

Hi there, I'm currently using the package with the defaultCountry prop set to "FR" as most numbers are French. However some numbers have different formats, eg an initial value for the component may be a UK number "+44.....".

import React, { useState } from "react";
import "react-phone-number-input/style.css";
import PhoneInput from "react-phone-number-input";
import fr from "react-phone-number-input/locale/fr";

export default function App() {
  // If number coming in from DB isn't French...
  const [phone, setPhone] = useState("+44788977366");

  return (
    <div className="App">
      <h1>Phone numbers</h1>

      <PhoneInput
        initialValueFormat="national"
        labels={fr}
        defaultCountry="FR"
        countries={["FR", "GB"]}
        value={phone}
        onChange={setPhone}
      />
      <p>{phone}</p>
    </div>
  );
}
Screenshot 2021-03-23 at 15 58 56

Is there any way I can set defaultCountry to be updated to match the initial value? Or force an update to the correct flag?

Or failing that are there any utility functions perhaps to determine the countryCode from the number? I could then use this to run a useEffect

Many thanks!

https://codesandbox.io/s/phone-numbers-1l9pi?file=/src/App.js:0-628

catamphetamine commented 3 years ago

Is there any way I can set defaultCountry to be updated to match the initial value? Or force an update to the correct flag?

Remove countries and see if it works.

andregoldstein commented 3 years ago

Thanks, unfortunately it doesn't.

catamphetamine commented 3 years ago

Hmm, looks like +44 7889 77366 doesn't belong to any country. https://libphonenumber.appspot.com/phonenumberparser?number=%2B44+7889+77366&country=RU

What icon would you suggest the library show in such case? Will "international" icon be appropriate?

andregoldstein commented 3 years ago

Thanks! You're absolutely right, apologies about that! When I add the extra digit all works as expected!

catamphetamine commented 3 years ago

I have still fixed the bug though: https://gitlab.com/catamphetamine/react-phone-number-input/-/commit/779b130247b0ba25d1f7d7650530bba2bc8c2d03 Your demo doesn't show France now in the case you've described: https://codesandbox.io/s/phone-numbers-forked-8b1cy?file=/src/App.js

andregoldstein commented 3 years ago

That's awesome, thanks so much for speedy response 👍