skip to Main Content

I need to format my input value to use a mask for BRL currency

Here is my input

<InputAnimation
required
type={"number"}
placeholder={" "}
label={"Valor"}
onChange={event=>setValue(event.target.valueAsNumber)}
value={value}
/>

I tried many tutorials, however most shows how to do it in jQuery or JS, and that doesn’t work well for React+Typescript

2

Answers


  1. Chosen as BEST ANSWER

    Here is the way I used to fix this:

    <InputAnimation required type={"text"} placeholder={" "} label={"Valor"} id="userInput" onChange={formatNumberToBRL} value={formattedValue} />

    And the function:

    function formatNumberToBRL(event: React.ChangeEvent<HTMLInputElement>): void {
        // Remove any non-numeric characters from the input
        let userInput: string = event.target.value.replace(/[^0-9]/g, '');
    
        if (userInput === '') {
          // If the input is empty, set the formatted value to "R$ 0,00"
          setFormattedValue('R$ 0,00');
          setValue(0);
        } else {
          // Convert the input to a number and divide by 100 to get the value in BRL
          let userInputAsNumber: number = parseInt(userInput, 10) / 100;
    
          // Format the number as BRL currency
          let formattedNumber: string = `R$ ${userInputAsNumber.toFixed(2).replace('.', ',').replace(/(d)(?=(d{3})+,)/g, "$1.")}`;
    
          // Update the state with the formatted value and the user input
          setFormattedValue(formattedNumber);
          setValue(userInputAsNumber);
        }
    }
    

    So there is no need of additional component or lib.


  2. To format your input value to use a mask for BRL currency in React with Typescript, you can use a package like react-number-format or react-currency-format. Here’s an example of how you can use react-number-format.

    npm install react-number-format
    
    import NumberFormat from 'react-number-format';
    
    ...
    ...
    ...
    
    <NumberFormat
      required
      placeholder={" "}
      label={"Valor"}
      onValueChange={(values) => {
        const { value } = values;
        setValue(value);
      }}
      value={value}
      thousandSeparator={true}
      prefix={"R$ "}
      decimalScale={2}
    />
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search