Integrate react-international-phone with UI libraries
masterTo build a custom phone input using third-party UI libraries (like Material UI, Ant Design, or Chakra UI), you should combine three core elements:
- An input component from your UI library (e.g., Material UI's
TextField). - The
usePhoneInputhook to manage the phone number state and logic. - The
CountrySelectorsubcomponent (or a custom implementation usingFlagImageandparseCountry) to handle country selection.
This approach allows you to maintain the visual style of your existing design system while leveraging the phone validation and formatting logic of react-international-phone.
// Conceptual pattern for custom UI integration
const {
inputValue,
handlePhoneValueChange,
inputRef,
country,
setCountry
} = usePhoneInput({
defaultCountry: 'us',
value,
countries: defaultCountries,
onChange: (data) => onChange(data.phone),
});
// Use inputValue and handlePhoneValueChange in your UI component's value and onChange props
<YourUIComponent
value={inputValue}
onChange={handlePhoneValueChange}
inputRef={inputRef}
/>