skip to Main Content

mask input does not work with input from antd.

maybe the ref needs to be transferred somehow in a different way.

export const MaskedInput = () => (
  <TextMask
    mask={[/d/, /d/, /d/, /d/, /d/, /d/]}
    render={(textMaskRef, props) => (
      <Input
        {...props}
        ref={(inputRef) => {
          inputRef && textMaskRef(inputRef?.input);
        }}
      />
    )}
    placeholder={"4 numbers"}
  />
);

codesandbox

I tried to transfer the ref like this, but there was no effect

export const MaskedInput = React.memo(React.forwardRef((props, ref) => (
  <TextMask
    mask={[/d/, /d/, /d/, /d/, /d/, /d/]}
    render={(textMaskRef, props) => (
      <Input {...props}  ref={(inputRef) => {
        if (inputRef?.input) {
          textMaskRef(inputRef?.input);
          if (ref) {
            ref.current = inputRef?.input;
          }
        }
      }}
    />
    )}
  />
)));

2

Answers


  1. From my research, there seems to be a problem with ant input ref so you probably can’t use it

    Instead using a utility from text-mask called conformToMask

    import React, { useState } from "react";
    import TextMask, { conformToMask } from "react-text-mask";
    import { Input } from "antd";
    
    var fourDigitsMask = [/d/, /d/, /d/, /d/];
    
    export const MaskedInput = () => {
      const [value, setValue] = useState();
      const [maskedValue, setMaskedValue] = useState();
    
      const handleChange = (e) => {
        let maskedVal = conformToMask(e.target.value, fourDigitsMask, {
          guide: false,
        }).conformedValue;
        setValue(maskedVal.replace([/d/, /d/, /d/, /d/], ""));
        setMaskedValue(maskedVal);
      };
    
      return <Input value={maskedValue} onChange={handleChange} />;
    };
    

    codesandbox: https://codesandbox.io/p/sandbox/text-mast-input-antd-forked-76qylt?file=%2Fsrc%2FMaskInput.jsx%3A1%2C1-21%2C1

    Login or Signup to reply.
  2. Try this generic input masker where you pass the pattern

    import React, { useState } from "react";
    import TextMask, { conformToMask } from "react-text-mask";
    import { Input } from "antd";
    
    export const MaskedInput = ({ maskPattern }) => {
      const [value, setValue] = useState();
      const [maskedValue, setMaskedValue] = useState();
    
      const handleChange = (e) => {
        let maskedVal = conformToMask(e.target.value, maskPattern, {
          guide: false,
        }).conformedValue;
        setValue(maskedVal.replace(maskPattern, ""));
        setMaskedValue(maskedVal);
      };
    
      return <Input value={maskedValue} onChange={handleChange} />;
    };
    

    call it like

    <MaskedInput maskPattern={"pattren"}/>
    

    please validate your pattern first on https://regex101.com/

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search