how to use imask react dynamic mask?

2k Views Asked by At

I'm trying to use these two masks according to the number of digits. Visually it works, but when I send the form, the first mask is always selected. How to solve this? I'm using imask-react

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

There are 1 best solutions below

0
On

Try the dispatch function

{
    mask: [{ mask: "(00) 0000-0000" }, { mask: "(00) 0 0000-0000" }],
    dispatch: (appended, dynamicMasked) => {
      const number = (dynamicMasked.value + appended).replace(/\D/g, "");

      if (number.length > 10) {
        return dynamicMasked.compiledMasks[1];
      }

      return dynamicMasked.compiledMasks[0];
    },
  }