react-intl-tel-input icon indicating copy to clipboard operation
react-intl-tel-input copied to clipboard

Unable to set dial code(country code)

Open MaheshK02 opened this issue 7 years ago • 16 comments

after API response unable to change dial code (country code) in componentDidMount. Need to update this library @superhit0 because m using this function for both add and update feature.

MaheshK02 avatar Aug 31 '18 09:08 MaheshK02

@patw0929 your call

superhit0 avatar Aug 31 '18 14:08 superhit0

anyone is updating this library ? or do u know @superhit0 this kind of library ?

MaheshK02 avatar Sep 01 '18 10:09 MaheshK02

Sorry for the late reply, I am busy recently. Could you provide some demo code to reproduce this issue? Thanks.

patw0929 avatar Sep 01 '18 10:09 patw0929

@patw0929 on button click m calling changeCountry method to update country flag but its not working.

componentDidMount(){
     country_short_name:'in' // in for india (default)
  }

// method for update country flag
 changeCountry = () => {
    this.setState({
      country_short_name:'us' // us for united states
    });
  };

//render  component
 <IntlTelInput
          fieldId="error"
          preferredCountries={[this.state.country_short_name]}
          onPhoneNumberChange={ this.handler }
          onPhoneNumberBlur={ this.handler }
          value= {this.state.contact}
          css={ ['intl-tel-input', 'form-control error'] }
          utilsScript={ 'libphonenumber.js' }
      />`

MaheshK02 avatar Sep 01 '18 12:09 MaheshK02

Actually, it cannot change country without changing the value (phone number) now. We will plan this new feature: changing country (flag) by passing new defaultCountry.

patw0929 avatar Sep 01 '18 14:09 patw0929

@patw0929 do u have any idea how much time it will take ?

MaheshK02 avatar Sep 03 '18 08:09 MaheshK02

There is news on this topic?

vladdevops avatar Oct 11 '18 19:10 vladdevops

Currently you can set the dial code (country flag) based on the defaultCountry prop, however is there a way to dynamically change the flag for example re-rendering the country flag when the country is changed?

dongarchive avatar Oct 19 '18 15:10 dongarchive

@patw0929 how time it will take to fix this issue ?

MaheshK02 avatar Oct 20 '18 08:10 MaheshK02

Any updates on this issue? Looking forward for this feature.

sanjeevaniekv avatar Oct 31 '18 04:10 sanjeevaniekv

Any updates regarding setting country flag when filled form with data on update?, like in javascript version of this library(setCountry).

diliGp avatar Dec 12 '18 03:12 diliGp

Since the dialCode cannot be set directly, here is an alternative solution (also mentioned above): The third parameter of the onPhoneNumberChange prop function is an object with data about the currently selected country, containing the fields areaCodes dialCode iso2 name priority. To load the component with a dialCode value, set the defaultCountry using the retrieved iso2 value.

andreaswk avatar Feb 27 '19 09:02 andreaswk

@MaheshK02 I was facing the same issue, so I dig into the library itself and found a way to make this work. What you've to do is, save the iso2(as @andreaswk mentioned just above) value in db as well while adding. And create a reference for your IntlTelInput like below: First create a ref property in your constructor: like this this._country = React.createRef();

And then assign the IntlTelInput ref to this.country like below:

<IntlTelInput
          fieldId="error"
          preferredCountries={[this.state.country_short_name]}
          onPhoneNumberChange={ this.handler }
          onPhoneNumberBlur={ this.handler }
          value= {this.state.contact}
          css={ ['intl-tel-input', 'form-control error'] }
          utilsScript={ 'libphonenumber.js' }
          ref={elt => this._country = elt}
      />

and when you're fetching result from db to update, set the dial code like: this._country.setFlag( db_value.iso2 );

That's it. It saved me to do rework for looking other libraries and experiment them.

Hope it'll help you too.

diliGp avatar Mar 08 '19 04:03 diliGp

I did that in different way but @diliGp answer was inspiration for me (without creating new variable with ref): I use that with React Hook Form lib.

<Controller
    name="number"
    control={control}
    render={({field}) =>
      <>
        <IntlTelInput
          onPhoneNumberChange={(status, value, country) => {
            setValue('number', value.replace(/\D/g, ''));
            setValue('number_validation', status);
            setTimeout(() => {
              trigger('number');
            })
          }}
          defaultValue={getValues('number')}
          onSelectFlag={(data, t1, t2) => {
            if (!data || !Object.keys(t1).length)
              return
            setValue('country_code', t1.iso2.toUpperCase());
          }}
          containerClassName="intl-tel-input"
          inputClassName={`form-control ${errors && errors.number ? 'is-invalid' : ''}`}
          onlyCountries={['us', 'ca']}
          preferredCountries={['us']}
          format={true}
          style={{width: '100%'}}
          ref={ref => {
            if (ref) {
              ref.setFlag(getValues('country_code').toLowerCase());
            }
          }}
        /></>
    }
/>

I tried also use defaultCoutry prop but it worked only when I pass "static" value, but I needed to use dynamic value (retrieved from WS).

Great lib but I think it still needs few improvements :)

dominik-mrugalski avatar Jun 09 '21 07:06 dominik-mrugalski

Thanks to @dominik-mrugalski @diliGp I'm not v good in react and JS but after spending few hrs your code gave me the hint and I was able to come with a solution where I need to update the phone country code and value (Complete Phone number as per user saved In DB) and on a form I got multiple users drop-down list and on selecting a user auto-populating the phone number was required so here is my code:

using TypeScript with React

<Controller
        render={({ ref }) => (
            <IntlTelInput
                fieldName="phone"
                fieldId="phone"
                containerClassName="intl-tel-input"
                inputClassName="form-control pdglft phnoonly"
                placeholder={Strings.general.phoneNumber} maxLength={20}
                defaultValue={phone}
                autoHideDialCode="true"
                separateDialCode="true"
                style={{ width: '100%' }}
                preferredCountries={["sa", "ae", "qa", "om", "bh", "kw", "pk"]}
                useMobileFullscreenDropdown={false}
                autoComplete="on"
                onPhoneNumberChange={(valid: boolean, number: string, country: any) => {
                    const args = { 'valid': valid, 'number': number, 'country': country };
                    setPhone('+' + country.dialCode + number);
                    return phoneValue(args);
                }}
                ref={(ref:any) => {
                    if (ref && phone !== undefined) {
                        let formattedPhoneNumber = ref.formatNumber(phone, true);
                        ref.updateFlagFromNumber(formattedPhoneNumber, true);
                        ref.updateValFromNumber(formattedPhoneNumber, true);
                    }
                }}
            />
        )}
        control={props.control}
        name="phone"
    />

ismaililsa avatar Jun 18 '21 13:06 ismaililsa

@ismaililsa It's some kind of inception... More than a year ago I posted here my solution for this problem, later, you posted your solution based on my answer, and today, I'm using your code in my project! 😅 Of course, it's more complicated than the original code above, but still the same idea.

Thanks for cooperation! How cool is that!

dominik-mrugalski avatar Nov 07 '22 17:11 dominik-mrugalski