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

External change of value #377

Closed ElodieBatista closed 3 years ago

ElodieBatista commented 3 years ago

Hi,

I'm trying to do the same thing as @JohannCarfantan in issue https://github.com/catamphetamine/react-phone-number-input/issues/366 but in my case, I don't have the complete phone number.

Indeed, I'm doing a dial pad below your input phone number. When user clicks on a key of the dial pad, I want to complete the input phone number. So each time user clicks on a key of the dial pad, I change the state of the PhoneInput's value. It works fine BUT for some reason I don't get, the current defaultCountry automatically switches to "International" on the first setState. On the next ones, correct flag reappears. I really don't get it.

const [val, setVal] = useState('');

const onTypeKey = useCallback((key) => {
       [...] // here I get the current value of the input and I concatenate the key

       // ex: phoneNumber="+335" --> french flag disappears
       // ex: phoneNumber= "+3356" --> french flag reappears
    setVal(phoneNumber); 
}, []);

<PhoneInput
    placeholder="Enter phone number"
    value={val}
    onChange={setVal}
/>

<ul>
<li onClick={() => onTypeKey('1')}>1</li>
<li onClick={() => onTypeKey('2')}>2</li>
<li onClick={() => onTypeKey('3')}>3</li>
[...]
</ul>

I've been trying many different solutions all day and I can't make it work. I'm certainly doing something wrong and I'm asking your help on what.

catamphetamine commented 3 years ago

Hi.

It works fine BUT for some reason I don't get, the current defaultCountry automatically switches to "International" on the first setState

It's not clear what you mean. A picture would be better than words.

ElodieBatista commented 3 years ago

Sure. I guess a code sandbox is even better: https://codesandbox.io/s/jolly-minsky-7e8cl

To reproduce: 1) Click on whatever key on the dial pad below the input phone number ==> input will be completed with the key you choose but the french flag doesn't appear.

Screenshot 2021-01-07 at 09 20 47

2) Click again on whatever key on the dial pad ==> input is again completed with the key you choose and now it's working, the french flag appears.

Screenshot 2021-01-07 at 09 20 52

I tried to add default country as FR but the same behaviour is happening. I also tried with different countries and it's still the same.

catamphetamine commented 3 years ago

Seems to be working in the latest version.

https://codesandbox.io/s/inspiring-rhodes-god1e

ElodieBatista commented 3 years ago

It is. Thanks!