GithubHelp home page GithubHelp logo

goveo / react-international-phone Goto Github PK

View Code? Open in Web Editor NEW
259.0 2.0 47.0 1.93 MB

☎️ International phone input component for React

Home Page: https://react-international-phone.vercel.app/

License: MIT License

Shell 0.06% TypeScript 92.99% HTML 0.10% SCSS 3.35% JavaScript 2.87% CSS 0.63%
format input international number phone phone-input react react-component tel telephone react-international-phone react-phone phone-number typescript

react-international-phone's Introduction

react-international-phone

🤙 International phone input component for React

npm-version build-status-badge install-size-badge codecov downloads Semantic Release stars

Live demo: Storybook

demo-gif

Features

  • 😎 Easy to integrate - Just import and use, no need for the initial setup. Integrate with any UI library using a headless hook.
  • 🔍 Country guessing - Just start typing and the component will guess the country and format the phone. Country flags are rendered using Twemoji.
  • Lightweight - Low bundle size, no third-party dependencies.
  • 🌈 Easy to customize - Customize styles and component behavior using props.
  • Caret position handling - Typing in the middle of the input, selection and deletion feels naturally.
  • ✔️ Validation - Easily validate entered phone numbers using provided functions.

Installation

$ npm i react-international-phone

Basic usage

import { useState } from 'react';
import { PhoneInput } from 'react-international-phone';
import 'react-international-phone/style.css';

const App = () => {
  const [phone, setPhone] = useState('');

  return (
    <div>
      <PhoneInput
        defaultCountry="ua"
        value={phone}
        onChange={(phone) => setPhone(phone)}
      />
    </div>
  );
};

Documentation

Find the full API reference on official documentation.

Migration

You can encounter some breaking changes after update between major versions.

Checkout migration documents that contain a list of breaking changes and ways to migrate:
Update from v3 to v4
Update from v2 to v3
Update from v1 to v2

react-international-phone's People

Contributors

afzalh avatar baharalidurrani avatar goveo avatar jessetan avatar mattshipitfi avatar meerlineer avatar onlywei avatar semantic-release-bot avatar willianrod avatar ygrenzinger avatar ziemkowski avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

react-international-phone's Issues

Feat: Introduce Search Input in Country Dropdown

Is your feature request related to a problem? Please describe.
Currently, the library only has a search feature without an input field, and I believe this might not be very intuitive, making it challenging for less experienced users to quickly locate and select the desired country code. This leads to a frustrating experience for those who need to find the country code promptly.

Describe the solution you'd like
I would like to request the addition of a search field within the country dropdown. This would allow users to enter the name of the desired country, triggering a corresponding filter in the list of country codes. This enhancement would make the selection process faster and more accurate.

Describe alternatives you've considered
A viable alternative would be to retain the existing search functionality and introduce a property that enables direct input within the dropdown, thereby disabling the default search mode.

Additional context
This improvement would provide a smoother experience for users dealing with international phone numbers, saving time and reducing frustration when searching for specific country codes

Unable to increase width

Describe the bug
A clear and concise description of what the bug is.

To Reproduce
Steps to reproduce the behavior:

  1. Go to '...'
  2. Click on '....'
  3. Scroll down to '....'
  4. See error

Expected behavior
A clear and concise description of what you expected to happen.

Screenshots
If applicable, add screenshots to help explain your problem.

Desktop (please complete the following information):

  • OS: [e.g. iOS]
  • Browser [e.g. chrome, safari]
  • Version [e.g. 22]

Smartphone (please complete the following information):

  • Device: [e.g. iPhone6]
  • OS: [e.g. iOS8.1]
  • Browser [e.g. stock browser, safari]
  • Version [e.g. 22]

Additional context
Add any other context about the problem here.

Extend FlagEmoji component to support local src

Is your feature request related to a problem? Please describe.
If your application needs to work offline or in environments with limited internet connectivity, having local flag images ensures that the flags will be displayed even when the emoji characters might not be available due to missing fonts or resources.

Describe the solution you'd like
Extending the FlagEmoji component to support a local image source

Describe alternatives you've considered
None

Additional context
None

Firefox network error on all icons NS_BINDING_ABORTED ( But load after in another request )

Describe the bug
If we look into the network requests of the example: https://react-international-phone-storybook.vercel.app/?path=/story/phoneinput--default

We can see that all svg requested are duplicated the first time being NS_BINDING_ABORTED and the second time they do request correctly.

I can also see that one comes from (img) and the other from (lazy-img).

It works well in chrome and safari, this seems to be firefox only problem.

From what I saw: https://stackoverflow.com/questions/704561/ns-binding-aborted-shown-in-firefox-with-httpfox#:~:text=Then%20you%20will%20see%20the,so%20it%20temporarily%20ignores%20Expires.

https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=&ved=2ahUKEwijxMis982DAxV3EFkFHVYQAOYQFnoECBQQAQ&url=https%3A%2F%2Fcommunity.cloudflare.com%2Ft%2Fmoved-ns-to-cf-error-ns-binding-aborted-headers-missing%2F340304&usg=AOvVaw3FWYQpKhT6KOd6Zq9_6X-l&opi=89978449

Could be some missing flag in Cloudflare

To Reproduce
Steps to reproduce the behavior:

  1. Go to https://react-international-phone-storybook.vercel.app/?path=/story/phoneinput--default
  2. Open network tab
  3. Check that all icons appear two times
  4. And the first time all with NS_BINDING_ABORTED

Expected behavior

Icons should only appear one time in the network tab

Screenshots
image

Desktop (please complete the following information):

  • OS: OSX
  • Browser: Firefox
  • Version: 122

I need the country mask format for force number validation

I use react-hook-form and to force the user to enter a correct number, I need the mask format for validation

Usage example for solution:

      <PhoneInput
        defaultCountry="br"
        onChange={(phone, country, mask) => {
          console.log(phone, country, mask);
        }}
      />

Is it possible?

Fixed brazilian phones are marked as invalid

Describe the bug
Here in Brazil, there are phone numbers such as +55 49 3361 1800 (example from a local hospital), which lack 1 digit. They are valid, but the validatePhone function labels them as invalid. This was enough for me to disable phone validation for now. These are phones connected to cable lines and fixed on desks, not mobile phones.

To Reproduce
Steps to reproduce the behavior:

import { validatePhone } from "react-international-phone"

const phone = "+55 (49) 33611800";
const { isValid } = validatePhone(phone);
console.log(isValid)
// isValid shoud be true

Expected behavior
This number should be treated as valid

Additional context
Using the latest version, 2.3.2.
I think I could solve this by myself and improve formatting for Brazilian phones, but unfortunately I can't contribute in the coming weeks :(

Country Search

Hi, I love your component, thank you for sharing it.

I was wondering if you had cosidered adding a country search bar to the top of the dropdown? this would make things much easier for the end user and make this the best library out there.

Thanks! 👍

onChange callback is triggering at the time of loading

Hi,

I'm using the Phone component in my project and observed one issue related to it.

The onChange is called at the time of component loading. Ideally, it should call if there is a change in the country or phone value.

Created a Code sandbox demo to reproduce the fix.

Can you please help me to fix it?

Countries list with usePhoneInput hook

Hi!

I noticed that if I pass some list of countries in the countries prop in the usePhoneInput hook, <CountrySelector /> will anyway render all countries. Now it's just disabled select for countries not in my list of selected countries. How can I show only countries from my list?

Scroll to selected country every time the list opens

Is your feature request related to a problem? Please describe.
There is a scenario when you:

  • Open the list. The selected country is shown.
  • Scroll the list and move the selected country out of sight.
  • Close the list.
  • Open the list. The selected country is not shown.

But, if you:

  • Open the list. The selected country is shown.
  • Scroll the list and move the selected country out of sight.
  • Close the list.
  • Open the list. The selected country is not shown.
  • Type ando. Andorra is focused.
  • Close the list.
  • Open the list. The selected country is shown.

Describe the solution you'd like
I would like the list to always show the selected country when it's opened.

Australian phone number validations

Describe the bug
Australian phone numbers do not pass validation.

To Reproduce
Steps to reproduce the behavior:

Screenshot 2023-04-21 at 12 19 08 PM

Expected behavior

  • The above should pass validation and the submit button should be enabled.

Additional context

02 5550 4321 [A landline number in NSW or the ACT]
0491 570 159 [An Australian mobile number]
1300 975 707 [An Australia-wide local-rate number]
13 00 00 [An alternative Australia-wide local-rate number]
1800 160 401 [An Australia-wide freephone number]
+61 2 5550 4321 [An Australian landline number in international format]
+61 491 570 159 [An Australian mobile number in international format]

Expose `ref` property

Is your feature request related to a problem? Please describe.

I'm trying to use this component with Informed (https://github.com/teslamotors/informed), but it needs to set the ref for the input element in order to work.

Since this component uses ref for it internal purposes, it just ignores the ref property.

Describe the solution you'd like

The component should check if the ref is passed as prop, and if it is, use it instead of creating a new one.

Describe alternatives you've considered

None

Additional context
Add any other context or screenshots about the feature request here.

default country with router.locale

Describe the bug
first i a not sure it's a bug, but i am not sure it's not something that already exists so it's more of a question 🙏🏼

i am trying to set the default language dynamically using the router, maybe the way i am doing it is not the best way as i am having an error of an undetected iso2

To Reproduce

CODE

export function PhoneField(props: { required?: boolean }) {
  const { field, error } = useTsController<string>();
  const { label } = useDescription();
  const router = useRouter();

  console.log('router', router.locale, router.defaultLocale);
  const defaultCountryRouter = ((router.locale ?? router.defaultLocale) as CountryIso2) || 'fr';
  console.log('defo', defaultCountryRouter);

  return (
    <>
      <Label label={label} error={error} required={props.required} />
      <PhoneInput
        defaultCountry={defaultCountryRouter}
        value={field.value}
        onChange={field.onChange}
        className={cn('rounded', {
          'ring-1 ring-red-500': error?.errorMessage,
        })}
        inputClassName={inputClassNames}
      />
      <ErrorMessage {...error} />
    </>
  );
}
```

ERROR: Unhandled Runtime Error
TypeError: Cannot read properties of undefined (reading 'iso2')


**Expected behavior**
default country should be settled with the router

**Screenshots**
If applicable, add screenshots to help explain your problem.

**Desktop (please complete the following information):**

- OS: [e.g. iOS] macbook
- Browser [e.g. chrome, safari] chrome, arc
- Version Version 114.0.5735.198 (Build officiel) (x86_64)


Support multiple mask formats within a country

Is your feature request related to a problem? Please describe.

Many countries have multiple formats, especially between mobile and landline numbers.

For example: Australian’s expect to see the ... ... ... mobile format (which will also apparently apply to 05 numbers, but not 0550 numbers, soon) for our mobile phone input, and . .... .... landline format for the other inputs. The Australian format was changed from mobile to landline in #48, but really both formats need to be supported.

Describe the solution you’d like

Ideally the input would “just know” based on what has been entered.

For example, you could add a map of regex to mask to the end of the CountryData with another type....

['Australia', 'au', '61', '. .... ....', 0, [], {'/^04/': '... ... ...', '/^05(?!50)/': '... ... ...'}],

I wonder if the CountryData type is getting too convoluted though, and if it might be better to create a new structure with additional formats, and have parseCountry() add an additionalFormats property to ParsedCountry instead, using a new structure in the countryData.ts file, like...

export const additionalFormats: AdditionalFormats = {
  au:  {'/^04/': '... ... ...', '/^05(?!50)/': '... ... ...'},
};

Describe alternatives you’ve considered

For our use case, we know if we’re asking for a mobile phone or landline, so for us this would work with a boolean mobile attribute on the <PhoneInput> component, and there could be a separate mobile format.

I suspect many consumers of the component wouldn’t know (or care) if it’s going to be a mobile or landline number though. I also suspect some countries have more than two formats available.

Another option might be to take a callback to determine the mask based on the country and number entered so far, but I feel like that's just going to require any multi-national consumer of this component to reinvent the wheel, which shouldn't be needed considering the name of the project.

Preferred Countries

Is your feature request related to a problem? Please describe.
No.

Describe the solution you'd like
Other libraries such as https://patw0929.github.io/react-intl-tel-input/ have a preferredCountries prop that can be used to group a set of preferred countries at the top of the list.

This is just a prop of the form:

preferredCountries={['us', 'gb']}

Describe alternatives you've considered
Filtering the countries makes the non-preferred countries go away. I would much rather still show all countries, but have preferred countries show at the top like the other libraries.

Additional context
If given preferredCountries={['us', 'gb']}, the phone input will render like this:
image

showDisabledDialCodeAndPrefix and pass the dial code to the input value at the same time

Is there a way to "showDisabledDialCodeAndPrefix" the can access the "dial code" within the "onChange" function?
For example, I don't want to the user to edit the "Dial Code", and yet I need to pass it with the input value on input change.

I tried the "forceDialCode" prop, and while it does what I want, It triggers an "OnChange" event when the input loads, which triggers the validation for the input on the component mount, which is not what I want.

The "showDisabledDialCodeAndPrefix" combined with "disableDialCodeAndPrefix" does exactly what I want "visually", but the "dial code" itself is not getting passed to the value, how can I access it?

Flickering value and placeholder during re-rendering

I'm writing to report a bug I encountered while using the "react-international-phone" package. The issue is related to the placeholder value that is being displayed every time the component re-renders.

Specifically, when the component has a value, the placeholder is displayed briefly before the actual value is shown. This behavior occurs every time the component re-renders, causing a noticeable flicker.

I have tried to address this issue on my end, but without success. I would like to request your assistance in resolving this problem. I'm happy to provide any additional information or to assist in any way I can.

The following snippet produces the issue.

import React from "react";
import { useTranslation } from "react-i18next";

import { Form, FormItemProps } from "antd";
import {
  PhoneInput as Input,
  PhoneInputProps,
} from "react-international-phone";
import "react-international-phone/style.css";

const PhoneInput: React.FC<PhoneInputProps & FormItemProps> = React.memo(
  ({ ...props }) => {
    const { t } = useTranslation("validation");
    const form = Form.useFormInstance();
    const value = Form.useWatch(props?.name || "");

    const onChange = (data: string) => {
      if (!data) return;
      if (!!props.name) form.setFieldValue(props.name, data);
    };

    const style = () => {
      if (!!props.disabled)
        return {
          backgroundColor: "rgba(0, 0, 0, 0.04)",
          color: "rgba(0, 0, 0, 0.25)",
        };
      return {};
    };

    return (
      <Input
        {...props}
        placeholder={`${t("placeholders.phone_number")}`}
        initialCountry="nl"
        value={value}
        onChange={onChange}
        inputStyle={style()}
      />
    );
  }
);

export default PhoneInput;

Vite module federation error while consuming in host

Describe the bug
Vite module federation doesn't work, when used in a host project, the following error pops up.

To Reproduce
Steps to reproduce the behavior:

  1. Setup vite module federation & expose a simple component for the phone input
  2. Consume that component in host
  3. Crashes the site

Expected behavior
Should not crash site and show the phone input

Screenshots
If applicable, add screenshots to help explain your problem.

Desktop (please complete the following information):

  • OS: All
  • Browser All
  • Version All

Smartphone (please complete the following information):

  • Device: All
  • OS: All
  • Browser All
  • Version All

Additional context

__federation_shared_react.js:9 Uncaught TypeError: Cannot read properties of null (reading 'useRef')
    at r.useRef (__federation_shared_react.js:9:6177)
    at e.usePhoneInput (__federation_expose_MuiPhone-1cb13654.js:9:23177)
    at e.PhoneInput (__federation_expose_MuiPhone-1cb13654.js:9:13227)
    at renderWithHooks (react-dom.development.js:16305:18)
    at mountIndeterminateComponent (react-dom.development.js:20074:13)
    at beginWork (react-dom.development.js:21587:16)
    at HTMLUnknownElement.callCallback2 (react-dom.development.js:4164:14)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:4213:16)
    at invokeGuardedCallback (react-dom.development.js:4277:31)
    at beginWork$1 (react-dom.development.js:27451:7)

Returning E164 format string value when using usePhoneInput hook with own UI input

Hi, thanks for this great library -- it's easy to implement with existing input components (material ui v4), so that's the approach I'm taking with the usePhoneInput hook.

The challenge I have is how to ensure that the phone number string value returned is in E164 format (e.g. +447810182855) rather than the formatted value that the component returns (e.g. +447810 182855 with hideSpaceAfterDialCode: true, or +44 7810 182855 with default configuration). The number is always formatted, but I would like to save the E164 format value regardless of what the component renders.

Given that the hook returns a phone string that is formatted correctly for the input, can there be an option for the handlePhoneValueChange function to (also) return an unformatted / E164 format value?

Describe alternatives you've considered
I've applied a replace to the string before saving newValue.replace(/[^+0-9]/g, '') but this causes issues with the cursor placement, so I've had to force that to the end with metadata.cursorPosition = unformattedValue.length in the onPhoneUpdate function. This is not ideal, so I would like the ability to manage a E164 format string value and the formatted value separately.

Selecting a country using CountrySelectorDropdown with Enter key is submitting form

Describe the bug
When using the react-international-phone in a form, selecting a country using the dropdown is submitting the form.

To Reproduce
I created a codesandbox with a sample code to reproduce the issue. https://codesandbox.io/s/react-international-phone-issue-drftc6?file=/src/App.js:1265-1353

Steps to reproduce the behavior:

  1. Using only the keyboard press tab to focus the country selector
  2. Press enter to open the dropdown
  3. Select a country by pressing Enter | Return
  4. You should see in the console that the form was submitted.

Expected behavior
When selecting a country I'm not expecting to submit the form with the current values, because I'm still going to fill my phone number and/or other inputs. Having that in mind, we should prevent the default behavior when pressing Enter inside the dropdown.

Screenshots
If applicable, add screenshots to help explain your problem.

Desktop (please complete the following information):

Screen.Recording.2023-08-17.at.12.43.09.mov
  • OS: [e.g. iOS]
  • Browser Arc
  • Version 1.3.0 (40706) (Chromium Engine Version 115.0.5790.170)

Smartphone (please complete the following information):

  • Device: iPhone 14 Pro
  • OS: iOS 16.6
  • Browser: Safari
  • Version: 16.6

Additional context
Add any other context about the problem here.

The automated release is failing 🚨

🚨 The automated release from the master branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you can benefit from your bug fixes and new features again.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can fix this 💪.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the master branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here are some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


Invalid npm token.

The npm token configured in the NPM_TOKEN environment variable must be a valid token allowing to publish to the registry https://registry.npmjs.org/.

If you are using Two Factor Authentication for your account, set its level to "Authorization only" in your account settings. semantic-release cannot publish with the default "
Authorization and writes" level.

Please make sure to set the NPM_TOKEN environment variable in your CI with the exact value of the npm token.


Good luck with your project ✨

Your semantic-release bot 📦🚀

Vite module federation

Discussed in #70

Originally posted by raffidahmad August 9, 2023
Cant seem to get it to work with module federation getting this error and unable to identify the cause

Uncaught TypeError: r is null
    Qr React
    usePhoneInput __federation_expose_UserManagement-f2d6de70.js:1040
    PhoneInput __federation_expose_UserManagement-f2d6de70.js:1040
    React 15
    notifyComponents index.js:4246
    replaceState index.js:4544
    applyActionsToStore index.js:2874
    queueOrPerformStateUpdate index.js:2898
    setRecoilValue index.js:2941
    useSetRecoilState index.js:5388
    g __federation_expose_UserManagement-f2d6de70.js:1028
    b __federation_expose_UserManagement-f2d6de70.js:1028
    onClick 
```</div>

country code clash for the Russia and Kazakhstan

Hi,

Recently I'm trying the validation with the usePhoneValidation hook and got to know that it's returning false for Russia. After the initial investigation, I found an interesting thing both Russia and Kazakhstan share the same code as '7', with that the validation is failing and the country is not updating. I tried in your storybook also and found the same. I also checked the country's data and found both are the same.

image

image

Below is the reason for it, which was found in Google.

image

Can you please update that change?

Using custom countries lists throws fatal error

Describe the bug
There is a fatal error when switching between custom country lists in the PhoneInput component. For example, if I want to use only North American countries:

  const countries = defaultCountries.filter(country =>
    ['ca', 'us', 'mx'].includes(country[1])
  );

and switch between them during runtime:

countries = {condition ? countries : defaultCountries}

In my Nextjs 13.4.9 environment I experience this error:

Unhandled Runtime Error

TypeError: t is undefined
Call Stack
D
node_modules\react-international-phone\build\index.mjs (1:7491)
Q
node_modules\react-international-phone\build\index.mjs (1:13387)
renderWithHooks
node_modules\next\dist\compiled\react-dom\cjs\react-dom.development.js (10697:0)
updateFunctionComponent
node_modules\next\dist\compiled\react-dom\cjs\react-dom.development.js (15180:0)
beginWork$1
node_modules\next\dist\compiled\react-dom\cjs\react-dom.development.js (17324:0)
beginWork
node_modules\next\dist\compiled\react-dom\cjs\react-dom.development.js (25689:0)
performUnitOfWork
node_modules\next\dist\compiled\react-dom\cjs\react-dom.development.js (24540:0)
workLoopSync
node_modules\next\dist\compiled\react-dom\cjs\react-dom.development.js (24256:0)
renderRootSync
node_modules\next\dist\compiled\react-dom\cjs\react-dom.development.js (24211:0)
recoverFromConcurrentError
node_modules\next\dist\compiled\react-dom\cjs\react-dom.development.js (23446:0)
performSyncWorkOnRoot
node_modules\next\dist\compiled\react-dom\cjs\react-dom.development.js (23707:0)
flushSyncWorkAcrossRoots_impl
node_modules\next\dist\compiled\react-dom\cjs\react-dom.development.js (9970:0)
flushSyncWorkOnAllRoots
node_modules\next\dist\compiled\react-dom\cjs\react-dom.development.js (9928:0)
processRootScheduleInMicrotask
node_modules\next\dist\compiled\react-dom\cjs\react-dom.development.js (10072:0)
scheduleImmediateTask/<
node_modules\next\dist\compiled\react-dom\cjs\react-dom.development.js (10243:0)

To Reproduce
Steps to reproduce the behavior:

  1. Create a React component that implements <Phone Input />
  2. Pass a conditional country list to the countries prop.
  3. In a session, switch between country lists by toggling the condition.
  4. See error

Expected behavior
No fatal errors when switching between country lists.

Desktop:

  • OS: Windows 11
  • Browser: tested on newest versions of Firefox, Chrome and Safari

Additional context
I tested this error in a Create React App as well as Nextjs with similar results. I believe this error has to do with improper indexing given to React. The workaround I'm currently using is to duplicate the component, and pass in the proper component at runtime:

  const phoneInput1 = () => (
    <PhoneInput key="pi1" {...phoneInputConfig} countries={countries} />
  );

  const phoneInput2 = () => (
    <PhoneInput key="pi2" {...phoneInputConfig} countries={defaultCountries} />
  );

return (
      {condition && phoneInput1()}
      {!condition && phoneInput2()}
);

node combability issues with build pipelines

Hi,

Thanks for creating the package it helped me a lot. I'm facing issues with the node version in my build pipeline. In the package, you have used 16. x.

image

While I'm using 18. x of the @types/node version. I tried to downgrade the version to 16. x in my local. However, it's not working the build pipelines.

Below is the error.
image

Do you definitely need that version? Can you please help me to fix it?

Prefill does not work with React Hook Form

I am using PhoneInput with React Hook Form as follows:
image
image

When I am editing my form I want the field to get prepopulated with previous value. For that I am using react hook form's setValue Method:
image

If my previous value is Indian phone number it gets prepopulated but if its other than Indian phone number it does not get prepopulated.

Please provide solution for this. Thanks!

Auto fill does not work correctly

Describe the bug
My browser remembers phone numbers I entered before.
Numbers could be with or without country code.
i.e.
0919044123
+421919044123

When I select such a number in Chrome/Safari either on mobile or desktop, the number inserted as +919044113 or +0919044123

The current country code is ignored and/or not updated

To Reproduce
Steps to reproduce the behavior:

  1. Just try to auto fill the number in any browser

Expected behavior
I would expect that

  • if autofill number is without country code then the selected country will remain unchanged and number will be prefixed with the country code.
  • if autofill number is with country code, then it will inserted as is and the country/flag changes accordingly

Desktop (please complete the following information):

  • OS: OSX
  • Browser: chrome, safari

Smartphone (please complete the following information):

  • Device: iPhone
  • OS: iOS latest

Validation Estonia numbers

The issue is found in Estonian number validation. For example, this format +372 XXXX XXXX is not considered as valid, but it is the actual format. It would be great if this could be fixed.

Inconsistent Phone Number Validation for Specific International Numbers

Describe the bug
The phone number validation fails for certain numbers in the application https://react-international-phone-storybook.vercel.app/?path=/story/validation--default. These numbers are considered valid by Google's libphonenumber library and are validated correctly on https://intl-tel-input.com/examples/validation.html.

To Reproduce
Steps to reproduce the behavior:

  1. Go to 'https://react-international-phone-storybook.vercel.app/?path=/story/validation--default'
  2. Enter one of the affected phone numbers (e.g. +31614621316)
  3. See validation error, although the number should be considered valid

Expected behavior
The numbers should validate properly according to the Google's libphonenumber library as seen on https://intl-tel-input.com/examples/validation.html.

Affected Numbers and Countries:

  • Netherlands: +31614621316
  • Brazil: +55 983 042 9980
  • China: +86 10 6468 2001
  • Germany: +49 69 2711 5111
  • Ireland: +353 1 679 3958
  • Israel: +972 337 53200
  • Japan: +81 3 5405 8800
  • Korea (South): +82 2 3788 0100
  • Malaysia: +60 3 87763095
  • New Zealand: +64 9977 9912
  • Philippines: +63454571127

Additional context
The majority of test cases are taken from https://www.staralliance.com/en/airline-contacts or https://zadarma.com

E164 formatted value

Is your feature request related to a problem? Please describe.

When saving the value to a database, we should be storing an E164 value. There doesn't seem to be a way to retrieve such a value.

We provide an E164 formatted value to the component and should be able to only ever handle E164 values as a consumer of this component.

Describe the solution you'd like

Ideally the onChange(phone) value would be an object with multiple values such as phone, country, e164, dialCode, etc. so the subscriber can use object destructuring to get the info they care about, e'.g. onChange(({ e164, country }) => ...

Since that would be a breaking change, I imagine it would be opted into via an argument/parameter (and then maybe changed in your next major version?). The nice thing about it though is future additions to that object would no longer be breaking changes.

Describe alternatives you've considered

I'm not sure if simply stripping non-numeric values is sufficient (is it?). That's what I'm doing now but I'm not sure if there are values I'm not aware of that would fail to validate on the server with Google's libphonenumber when given only digits.

Using something like awesome-phonenumber seems like extreme overkill.

Additional context

One problem with formatting the onChange value from the user's side is that it would surely get passed right back into the component which could cause an update loop, which we already see:

As it is today, our E164 value instantly triggers an onChange on mount. Being able to compare our existing E164 value with the new value would allow us to avoid an update loop while maintaining a database-ready E164 value in our state instead.

Additional note

Your Storybook has an e164 page, but it doesn't seem to make sense or function correctly (and there is no story source view configured). I'm assuming it was meant to show us how to get E164 values?

P.S.

If the headings in this ticket are easier to read than usual, you may want to update the issue templates to use ### instead of **

Improve docs

I think the docs should be improved because it is a bit confusing how the api works.
Specifically, I am confused about the styles.

            <PhoneInput
              countrySelectorStyleProps={{ buttonClassName: 'px-2' }}
              defaultCountry="us"
              inputClassName={`w-full ${isValid ? '' : 'border-red-500'}`}
              onChange={(e) => {
                handlePhoneNumber(e);
              }}
              inputProps={{
                onBlur: () => {
                  isPhoneValid(`+${phoneNumber}`);
                },
              }}
            />

I'm trying to access 'listItemClassName' and I can't access it.
It would be nice to have examples.

Jest error when trying to test a component that uses the lib

Describe the bug
Jest error when trying to test a component that uses the lib

To Reproduce
Steps to reproduce the behavior:

  • Try to test a component that uses the lib

Expected behavior
Pass the tests

Screenshots
image

Additional context
Jest version

"jest": "^29.1.2",
"jest-environment-jsdom": "^29.1.2",

Can't set value on PhoneInput ??

<PhoneInput onChange={(phone) => { setPhoneNumber(phone) }} initialCountry="ma" />

i can't set the value to what i want cause it doesn't exist

Support all ISO 3166-1 alpha-2 country codes?

Our website allows people to enter their country, including options like "Cayman Islands" (KY), before they get to the step where they enter their phone number. However, we cannot set the Cayman Islands as the defaultCountry for such users.

It would be great if this component could support all 249 assigned country codes: https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2

We could add additional countries ourselves, but we'd have to look up the dialing code and format for each one ourselves, and maintain. Without this, we will have to fall back to having no defaultCountry; and when the user enters a Cayman Islands phone number, for example, the component will incorrectly show a US flag.

Cannot update a component (`Page`) while rendering a different component (`MuiPhone`).

Describe the bug
Copying the MuiPhone example from the docs
There is a React Console Error.

Cannot update a component (Home) while rendering a different component (MuiPhone). To locate the bad setState() call inside MuiPhone,

To Reproduce
Copy the Material UI example Component from here and pass in a value and onChange function

// home.tsx
const [phone, setPhone] = useState("+1");

  const handlePhoneValueChange = (value: string) => {
    setPhone(value);
  };
  
   <MuiPhone
        value={phone}
        onChange={handlePhoneValueChange}
      />

Open developer console in browser to see error

Expected behavior
Should not show errors

Screenshots
If applicable, add screenshots to help explain your problem.

Desktop (please complete the following information):

  • OS: [MacO]
  • Browser [Chrom]
  • Version [e.g. 112]

Additional context

Screenshot 2023-04-30 at 8 11 55 PM

Missing params from the handlePhoneValueChange with usePhoneInput

Hi @goveo,

Thanks for fixing the country code clash for the Russia and Kazakhstan #46 issue. I saw the latest migration and it's working if I go with the below way.

image

But I'm using it with an MUI library and implemented using the demo that you added in the docs. In that, we are relying on the usePhoneInput hook. The onChange event from the text field is passed to the handlePhoneValueChange method and it'll return a string that is entered in the text field. In this way the country value is reset and the validation is failing again.

It would be very helpful if you can provide the same way of returning two params as phone and country to the hook also. It's kind of an urgent fix for me.

bitmoji

Add Locales

Adding support for different locales and country names can be a valuable feature request, especially if you want to make the component more user-friendly and inclusive for a global audience. Localization is essential for providing a better user experience and ensuring that your component can be used effectively by people from various regions around the world.

TypeScript module `.d.ts` files include unreachable code

Describe the bug
The TypeScript modules .d.ts files include unreachable code, making VS Code think something exists when it doesn't, e.g. I was hoping to use formatPhone() and copied how it is used in src/utils/handlePhoneChange.ts, but when I tried to run the code, I got an error saying the functions I tried to use didn't exist.

To Reproduce
Steps to reproduce the behavior:

  1. Add this to some TypeScript code:
import { defaultCountries } from 'react-international-phone';
import { guessCountryByPartialNumber } from 'react-international-phone/build/utils';
const countryGuessResult = guessCountryByPartialNumber({phone: 'phone', countries: defaultCountries});
  1. Notice that VS Code (and probably any other code editor) thinks it's fine.
  2. Try to run/compile the code
  3. See an error like this:
[commonjs--resolver] Missing "./build/utils" specifier in "react-international-phone" package

Expected behavior
Either the TypeScript modules .d.ts files should not exist or reference unreachable code, or the code should be made available in the built files, e.g. it would be nice to be able to use the helper functions to format phone numbers in other use cases besides in form inputs.

About Chinese mobile phone number template

Your plug-in is very good, but it is a little unfriendly to Chinese users. The format of Chinese mobile phone number is +86 xxxxxxx xxxx, and the format of the plug-in is +86 xx-xxxxxxxxx. Can you support the template format of Chinese mobile phone number

Or can you show me how to do it to achieve what I want,Thank you~

image

image

The automated release is failing 🚨

🚨 The automated release from the master branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you can benefit from your bug fixes and new features again.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can fix this 💪.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the master branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here are some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


Cannot push to the Git repository.

semantic-release cannot push the version tag to the branch master on the remote Git repository with URL https://[secure]@github.com/goveo/react-international-phone.git.

This can be caused by:


Good luck with your project ✨

Your semantic-release bot 📦🚀

MUI Design - Causes text formatter not to work

Describe the bug
I have the code example for Material UI from https://react-international-phone.vercel.app/docs/Advanced%20Usage/useWithUiLibs
However on my setup , the text formater doesnt work .
This seems MUI specific and I havent deviated from the MUI example above.

Except updating this code for FlagImage
value={country}
onChange={(e) => setCountry(e.target.value)}
renderValue={(value) => (
<FlagImage iso2={value.iso2} style={{ display: 'flex' }} />
)}
>

Add search in the CountrySelector dropdown

Is your feature request related to a problem? Please describe.
Currently, the CountrySelector dropdown does not seem to be searchable.

Describe the solution you'd like
An enhancement to the existing CountrySelector dropdown would be to make the list of countries searchable. This will improve UX.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.