IonInput and input masking in React

Hey all,

I think I was able to get this working by using imask directly. This seems to work for me, can anyone confirm?

const MaskedIonInput = ({ value, onChange }: Props) => {
  const maskRef = useRef<IMask.InputMask<any> | null>(null);

  const inputCallback = useCallback(async (input) => {
    if (!input) {
      return;
    }
    const nativeInput = await input.getInputElement();
    const mask = IMask(nativeInput, {
      mask: Number,
      thousandsSeparator: ",",
    }).on('accept', (e: any) => {
      onChange(mask.value);
    }).on('complete', (e: any) => {
      onChange(mask.value);
    });

    maskRef.current = mask;
  }, []);

  return (
    <IonInput value={value} ref={inputCallback} />
  )
}

Usage would be:

const MyComponent: React.FC = () => {
  const [myValue, setMyValue] = useState('');

  return (
    <MaskedIonInput value={myValue} onChange={(v) => setMyValue(v)} />
   );
}

Probably would want to clean up the ref with a useEffect cleanup or something.

3 Likes