Kelly Milligan
Kelly Milligan

Reputation: 588

Storing numbers as initial values in formik, react-final-form, react-hook-form

I am wondering folks thoughts on this scenario: you have an input that represents a price of an item, like filling out a form for an item that users purchase. you have a few utilities to have the number have a certain number of decimals, not be negative, etc. Of course the value in the input itself needs to be a string, since it's html at the end of the day. what would be some benefits/drawbacks for both options:

I feel like there are tradeoffs to both approaches, but that keeping things as a string always is more decoupled, which comes with some extra code in places like the submit, validation(checking if the value is greater than 0 for example, have to convert to number before validating), but keeps things simple at the form level.

The flipside is if you have a price input field in a lot of places in your app, it may make more sense to do the work of maintaining the number as the value in the form state, and being able to just submit the form state to the api without worrying that it's the right type/value sounds nice and convenient.

Upvotes: 1

Views: 2195

Answers (2)

Bill
Bill

Reputation: 19298

Input return string by default. You can refer to the spec below:

https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement

However, you can use valueAsNumber, but you need to be careful with NaN. When a parse is failing it will fall back to that.

valueAsNumber

double: Returns the value of the element, interpreted as one of the following, in order:

  • A time value
  • A number
  • NaN if conversion is impossible

Here is an implementation in react-hook-form, you can also do parse like what Erik (author of React Final Form and Redux Form) suggested above.

<input type="number" name="number" ref={register({ valueAsNumber: true, min: 4 })} />

All those libs that you have pinged all support one way or another to parse to number.

Upvotes: 0

Erik R.
Erik R.

Reputation: 7272

At the end of the day, the DOM inputs work with strings. Historically form data was submitted as query parameters, remember.

React Final Form has had parse and format props from Day 1, but in my experience, I would advise against using them. My recommendation: Keep your form values strings, and parse them into Numbers, if you must, at the time of submission.

Upvotes: 2

Related Questions