Currency converter app in React and Mlyn
👋 Let build a currency converter app:
The application should allow to edit the amount in the input fields and change currency. The amount in another input should change in the base of the conversion rate.
For a working example see this codesandbox (It also contains an advanced example).
First of all, we need to define our data domain. We need to take a currency as a reference point, let use USD:
Now we can setup the root state:
Yeah, that’s all boilerplate we need. And finally some JSX:
Operation state$.baseAmount
created a read/write lens to baseAmount
property. Calling state$.baseAmount()
will return its current value and state$.baseAmount(1)
will change the baseAmount
value. The update will bubble to the root state, cause encapsulated object is immutable. Also, you can subscribe to this value. This enables 2-way binding.
Same thing for state$.currencies[0]
, it will read/write the first element of the currency
array.
Now let write an incomplete version of the Currency
component.
Mlyn.select
is a wrapper over the plain select
element, it has a property bindValue
which accepts a read/write value, and creates a 2-way binding to it. Internally Mlyn.select
will observe currency$
value, and re-render when it’s changed. When a selector option will be selected currency$
(and hence the root state) will be updated.
To write the input we can’t just bind amount$
to it, cause we need to display the derived value of the currency:
Ok. This will be the hardest part.
One of the good things about 2-way binding is that you can wrap binded value within a function, that will perform read/write derivation logic. So let create a function that will convert amount in a currency to/from USD amount:
The above function is a simplified version, in reality we should do some input validation:
Now you can use pass the converted currency lens to the amount input:
For more examples and docs about mlyn, I invite you to check the github repo page.