Percentage mask with React-input-Mask in React js with typescript

Asked

Viewed 343 times

-1

I have to create a mask for an input in the project we are already using the React-input-Mask https://github.com/sanniassin/react-input-mask#beforemaskedstatechange

The solution does not necessarily need to use React-Input-Mask.

He says a lot of things.

But to create a dynamic mask with the % symbol that needs to stand next to the number taking a step.

here is the link of a sandbox code I found of a guy who create a mask for Cpf and cnpj https://codesandbox.io/s/brava-react-masked-input-8xe2p?file=/src/App.js

tbm am using formik

Down as the field should be and the mask behavior of the mask.

The field must be blank so I can insert A PERCENTAGE;

The field should only accept NUMBER above 1 up to 100, including 100;

Field accepts only integer values;

Field must not accept LETTERS or special character;

The user must display the % symbol in the field next to the number typed;

The user must view the inserted PERCENTAGE on screen;

<Input
        width="auto"
         value={formik.values.beneficiaries[index]["percentage"]}
         name={`beneficiaries.${index}.percentage`}
         id={"percentage" + index}
         optional={false}
         label="Porcentagem"
         mask={"999%"}
         maskPlaceholder={""}
         error={!!(errors.beneficiaries[index] && errors.beneficiaries[index}["percentage"])}
         errorDescription={errors.beneficiaries[index] ? errors.beneficiaries[index]["percentage"]: ""}
         change={formik.handlerChange}
         blur={formik.handleBlur}
         focus={handleOnFocus}
    />

the commented Mask is a property of the "Input-Mask where is the 9" it specifies that will receive number and the % only appears after typing the three numbers, I do not want to use jqueryMask, because we are already using React-Input-Mask in the project for it is more "simple".

Can be a solution without React-Input-Mask. I hope to have described my problem well in waiting :D

  • tried it like this: <MaskedInput name="porcento" mask="999%" value=values.porcento} onChange={handleChange} />

  • when doing so the input ceases to receive input values

1 answer

0


I got the solution without using a lib just using the toLocaleString https://www.w3schools.com/jsref/jsref_tolocalestring_number.asp

created a function

//regexs para converter e mascara.

 const convertMaskPercent = (value: string) => {
  return (parseInt(value.replace(/[^0-9]/g, "")) * 0.01).toLocaleString("pt-BR", { style: "percent" });
  
};

const removeCharactersAndSpecialCharacter = (value: string) => {
  return value.replace(/[^0-9]/g, "");
};

// mascara campo porcentagem      
const handlerChangeMaskPercent = (event: any) => {
    const { name, value } = event.target;

    if (Number.isNaN(parseInt(removeCharactersAndSpecialCharacter(value)))) {
      formik.setFieldValue(name, "");
    } else {
      var newValue = convertMaskPercent(value);
      formik.setFieldValue(name, newValue);
    }
  };

 // limitar valor até 100 é limpar valores maiores
  const onBlurMaskPercent = (event: any) => {
    let {name, value} = event.target
    let parseValue = parseInt(value)
      if(parseValue > 100 || parseValue < 0){
        formik.setFieldValue(name, "");
      }

  };

HOW THE INPUT TURNED OUT!


<Input
                                width="auto"
                                value={
                                  formik.values.beneficiaries[index][
                                    "percentage"
                                  ]
                                }
                                name={`beneficiaries.${index}.percentage`}
                                id={"percentage" + index}
                                optional={false}
                                label="Porcentagem"
                                maskPlaceholder={""}
                                error={
                                  !!(
                                    errors.beneficiaries[index] &&
                                    errors.beneficiaries[index]["percentage"]
                                  )
                                }
                                errorDescription={
                                  errors.beneficiaries[index]
                                    ? errors.beneficiaries[index]["percentage"]
                                    : ""
                                }
                                change={handlerChangeMaskPercent}
                                blur={onBlurMaskPercent}
                                focus={handleOnFocus}
                                maxCharacters={4}
                              />

```

Browser other questions tagged

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