In my form I have an "amount" field which should always display 2 decimal digits. So, for example if the user types 3, it should be converted to 3.00. If he types 3.1234525 it should become 3.12.
In order to do this I rely on the onBlur prop. Basically onBlur I run a function that formats the number correctly and I try to set the new value on the field.
Here's my code:
import { blur as blurField } from 'redux-form/immutable';
...
const mapDispatchToProps = {
blurField,
};
...
export default connect(mapStateToProps, mapDispatchToProps)(Amount);
class AmountContainer extends Component {
props: PaymentMethodPropsType;
formatAmount(event) {
const {
blurField,
} = this.props;
blurField('myForm', 'amount', formatNumber(event.currentTarget.value, 2));
}
/**
* Render method for the component
* @returns {Element<*>} the react element
*/
render() {
const {
t,
amountValue,
} = this.props;
const amountLabel = t('form')('amountLabel');
return (
<Amount
amountLabel={amountLabel}
amountValue={amountValue}
normalize={onlyNumbersDecimals}
onBlur={(event: Event) => this.formatAmount(event)}
validation={[
isRequired(t('validation')('amountRequired')),
number(t('validation')('amountNotNumber')),
]}
/>
);
}
}
Let's say I input the number 3 and then I move to the next field in the form. I can see the following actions being called:
{type: "@@redux-form/BLUR", meta: {…}, payload: "3.00"}
{type: "@@redux-form/BLUR", meta: {…}, payload: "3"}
As a result the input value remains 3. It looks like the initial onBlur event "overwrites" the one I trigger calling blurField