Skip to content

Instantly share code, notes, and snippets.

@mcmxc
Created January 8, 2020 12:21
Show Gist options
  • Save mcmxc/c43d9a2967e56fde5b76332fdc1fa83d to your computer and use it in GitHub Desktop.
Save mcmxc/c43d9a2967e56fde5b76332fdc1fa83d to your computer and use it in GitHub Desktop.
react-phone-number-input + ant design (antd) Input
import React, { useState, useCallback, forwardRef } from 'react';
import { Input } from 'antd';
import PhoneInput from 'react-phone-number-input/min';
import 'react-phone-number-input/style.css';
const PhoneInputComponent = forwardRef(({ onChange, ...props }, ref) => {
const handleChange = useCallback(e => onChange(e.target.value), [onChange]);
return <Input ref={ref} {...props} onChange={handleChange} />;
});
const App = () => {
const [phoneNumber, setPhoneNumber] = useState();
return (
<div className="app">
<PhoneInput
value={phoneNumber}
onChange={setPhoneNumber}
inputComponent={PhoneInputComponent}
/>
</div>
);
};
export default App;
@nguyenthanh1205tb
Copy link

nguyenthanh1205tb commented Jan 2, 2025

@mcmxc it works for me. Thanks!!!!
this is in Typescript:

import AntdInput, { InputProps, InputRef } from 'antd/es/input'
import classnames from 'classnames'
import React, { useImperativeHandle, useRef } from 'react'

interface Props extends InputProps {}
const Input = React.forwardRef<InputRef, Props>((props, ref) => {
  const inputRef = useRef(null)

  useImperativeHandle(ref, () => (inputRef.current as any)?.input ?? null, [])

  return ( <AntdInput ref={inputRef} {...props} /> )
})

Input.displayName = 'Input'
export default Input

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment