how to have 8 or 9 digit + DDD phone mask using react imask?

2.3k Views Asked by At

I'm using lib react imask to add mask to my inputs. In case of phone, it can support numbers with 8 or 9 digits. How can I resolve this dynamically?

8 digits -> mask '(00) 0000-0000'
9 digits -> mask '(00) 00000-0000'

const mask = {
  mask: '(00) 00000-0000'
};

const InputPhone: React.FC<InputProps> = (props) => {
  return <InputMask maskParams={mask} name='phone' {...props} />;
};
1

There are 1 best solutions below

2
On

Refer this: https://imask.js.org/guide.html#masked-dynamic

import { IMaskInput } from 'react-imask';

const mask = [{ mask: '(00) 0000-0000' }, { mask: '(00) 00000-0000' }];

const Home = () => (
  <IMaskInput mask={mask} name="phone" placeholder="Enter phone number here" />
);

export default Home;

Output:

Open in StackBlitz