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;
@mcmxc
Copy link
Author

mcmxc commented Oct 5, 2024

I'll update this later today or tomorrow, this approach is outdated

@mcmxc
Copy link
Author

mcmxc commented Oct 5, 2024

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