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
Just using the event.preventDefault will work:
formatAmount(event) {
const {
blurField,
} = this.props;
event.preventDefault();
blurField('myForm', 'amount', formatNumber(event.currentTarget.value, 2));
}
Hey so this is a little late but I've found an effective and simply way of going about this. I send in the on blur prop, bind the function to the forms scope, and use the built in redux-form function ( change ) to update the field value with the formatted value. The funny thing with this technique, is you need to use a setTimeout set the execution time to 0, for this to work properly. ex.
onBlur={e => {
let value = e.target.value;
* Format or update value as needed *
setTimeout(() => this.props.change(* FIELD NAME *, value));
}}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.