Search code examples
javascriptreactjsnumber-formattingvisual-web-developer

wrong behaviour of number format


So I'm using the NumberFormat library for building a placeholder, but it doesn't work how I wanted it to work, and I don't find the reason. The behavior of the input field is quite strange. The "$0" which should behave as a placeholder behaves as a character, so if the user types "120", the amount will actually be "1200".

Here's a video of how it works: https://media.giphy.com/media/sptBQiYqQr3B54rJFu/giphy.gif

But the correct behaviour would be to, when there is a 0, and the user inputs a value, the 0 should be replaced (you can check the google calculator, it does that).

<NumberFormat
                defaultValue={undefined}
                value={payoutInputValue}
                displayType="input"
                thousandSeparator
                decimalScale={2}
                prefix={getCurrencySymbol(currency)}
                allowLeadingZeros={false}
                allowNegative={false}
                getInputRef={numberInputRef}
                onValueChange={(values) =>
                  setPayoutInputValue(values?.floatValue || undefined)
                }
                disabled={disabled || isLoading}
                isAllowed={isDrawAmountAllowed(0, currency)}
                required
              />

and the setPayoutInputValue function:

const [payoutInputValue, setPayoutInputValue] = useState<number>(
    payout === 0 && isAmountParamValid ? amountParamParsed : payout
  );

I have not much experience with React, so if you could answer with basic terms, that'd be awesome. Thanks!

EDIT: managed to make it work! added placeholder attribute and value={undefined}


Solution

  • Try setting the hintText prop for NumberFormat, also give as an initial value undefined.

    <NumberFormat
      hintText="Some placeholder"
      value={this.state.card}
      customInput={TextField}
      format="#### #### #### ####"
    />