Search code examples
reactjsmaterial-designmasking

react-text-mask how to pass pattern in function react using material-ui form


This is my class

class PaypalAddPaymentForm extends Component {

  constructor (props) {
    super(props);
    this.state = {
     form: {
      cardNo: '',
     }
    }
  }

  onChange = (e, v) => {
    let field = e.target.name;
    let form = this.state.form;
    form[field] = e.target.value;
    this.setState({ form });
  }

  render () {
   return (
      <PaypalForm className="margin-top margin-horizontal">
        <FormGroup>
         <FormLabel>Card</FormLabel>
         <Input
          name="cardNo"
          inputComponent={CreditCardMask}
          onChange={this.onChange}
          inputProps={{ 'aria-label': 'card no' }}
          disableUnderline
         />
        </FormGroup>
      </PaypalForm>
    );
  }

}

I am using a library called react-text-mask Which basically masks it like this according to it's docs

function CreditCardMask (props) {
  return (
    <MaskedInput
      {...props}
       mask={[ /\d/, /\d/, /\d/, /\d/ ]}
       placeholderChar={'\u2000'}
       showMask={false}
     />
   );
}

Now what I want to do is make such a function for Masking that accepts pattern in it's function param, So that I can create a common masking function which takes in the pattern and masks the input field according to the masking params it gets;

Something like this function CreditCardMask (props, pattern) where pattern is the regex pattern I want the input to be masked like.

The material ui version that I am using is "material-ui": "^1.0.0-beta.12",


Solution

  • I suggest you can use high order function to wrap your component:

    function CreditCardMaskWrapper(pattern) {
      return (props) => {
        return (
          <MaskedInput
            {...props}
            mask={pattern}
            placeholderChar={'\u2000'}
            showMask={false}
          />
        )
      };
    }
    

    And then you can:

         const pattern = [ /\d/, /\d/, /\d/, /\d/ ];
    
         <Input
            name="cardNo"
            inputComponent={CreditCardMaskWrapper(pattern)}
            onChange={this.onChange}
            inputProps={{ 'aria-label': 'card no' }}
            disableUnderline
         />
    

    Good luck!