Change will mask a Textfield according to the choice in a Selectfield

Asked

Viewed 98 times

0

Good afternoon to you all. I am a beginner in Reactjs, I am working on the construction of a form and in the PHONE field I need the mask of this Textfield change according to the selection of the user in a Select, if the PHONE informed is RESIDENTIAL the mask will take the format (XX) XXXX-XXXX, if it is CELLULAR the format will be (XX) XXXXX-XXXX.

I’m using Materialui and I’ve made the phone masks RESIDENTIAL and MOBILE.

Select PHONE TYPE (Field where the user will select the type of phone to be filled in Textfield PHONE, must change the mask as chosen by the user).

<Select
 native
 value={value}
 input={
  <OutlinedInput 
   labelWidth={120}
   id="tipoTelefone"
  />
 }
 onChange={
  (event) => setFieldValue('typePhone', event.target.value)
 }
>
 <option value='1'>Telefone Fixo</option>
 <option value='2'>Celular</option>
</Select>

Textfield PHONE (Field that should change the mask as chosen by the user in Select PHONE TYPE).

<TextField
onChange={
(event) => setFieldValue('campoTelefone', event.target.value)
}
fullWidth
value={values.campoTelefone}
onBlur={handleBlur}
label="Telefone"
margin="normal"
variant="outlined"
InputProps={{
inputComponent: MaskRESIDENCIAL,
}}
id="campoTelefone"
autoComplete={"on|off"}

/>

Thanks in advance for your help...!!!

Tks,

Hebert Costa

1 answer

0

You can resolve this easily using the React-text-Mask library.

Take an example:

import React from 'react'
import MaskedInput from "react-text-mask";

function InputMaskCustomPhone(props) {
    const { inputRef, ...other } = props;
    return (
        <MaskedInput
            {...other}
            ref={ref => {
                inputRef(ref ? ref.inputElement : null);
            }}
            mask={(rawValue) => {
                if(rawValue.replace(/(\D)+/g,'').length > 10)
                {
                    return ['(', /\d/, /\d/, ')', ' ',/\d/, ' ', /\d/, /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/]
                } else {
                    return ['(', /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/]
                }

            }}
            guide={false}
        />
    );
}

function App(){
  return (
    <TextField
      onChange={(event) => setFieldValue('campoTelefone', event.target.value)}
      fullWidth
      value={values.campoTelefone}
      onBlur={handleBlur}
      label="Telefone"
      margin="normal"
      variant="outlined"
      InputProps={{ inputComponent: InputMaskCustomPhone }}
      id="campoTelefone"
      autoComplete={"on|off"}
    />
  )
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.