Created
January 8, 2020 12:21
-
-
Save mcmxc/c43d9a2967e56fde5b76332fdc1fa83d to your computer and use it in GitHub Desktop.
react-phone-number-input + ant design (antd) Input
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
We can extract the original input element from <Input />
instance.
Example with imask.js:
uNmAnNeR/imaskjs#163 (comment)
just checked, this peace of code still works with v4
doesn't work with the latest Antd https://stackblitz.com/edit/react-dg4xxp
Any luck getting this to work? I've been unsuccessful: ant-design/ant-design#49312 (comment)
I'll update this later today or tomorrow, this approach is outdated
react + react-dom - 18.3.1
antd - 5.20.4
react-phone-number-input - 3.4.8
import PhoneInput from 'react-phone-number-input';
import { forwardRef, useImperativeHandle, useRef } from 'react';
const MyInput = forwardRef((props, ref) => {
const inputRef = useRef(null);
useImperativeHandle(ref, () => inputRef.current.input, []);
return <Input placeholder={'(201) 555-0123'} {...props} ref={inputRef} />;
});
const PhoneNumberInput = () => {
const [value, setValue] = useState('')
return (
<PhoneInput
onChange={setValue}
value={value}
inputComponent={MyInput}
// ...props
/>
)
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Any solution you guys know of with v4?