Input field type "Currency" problem solved 💲💡

TechWorld with Nana - Jan 25 '20 - - Dev Community

Just recently we implemented a calculator for property yield. So in our calculator, there were some currency input fields, obviously, where user can enter purchase price etc. And these input fields needed to be formatted in German, since most of our users are German.

The problem

The annoying problem we had was, how to display the formatted number while also using it to calculate some other values, because <input type=“number” /> doesn’t allow displaying German format - 1.000,00.

UI example below:
UI Currency

Side note: we use React-Intl to format the number into a language-specific currency.

Solution

After trying out several options, we came up with the following simple solution:

We use the <input type=number” /> when input field is in focus and save the value in state as a number to use it in calculations. When the input field loses focus (onBlur callback), we switch the Input field to <input type=“text” /> to display the formatted number currency.

Code snippet below:
input field currency react

This way, in order to display and calculate the same value, we don’t have to transform it from number to string and vice versa. Also this requires minimal code change.


You can follow me on Twitter and YouTube.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player