I have a simple form field and I am trying to format and set the field value when onChange event is triggered using setFieldsValue which is not working.
I am trying to show the formatted value in the same text field.
Please find the sandbox link here codeSandbox
I dont want to create one more controlled component with state and set the value as I have 20 fields in the original form data. How could we set the form value on onChange itself.
You are loosing the value being set because the onChange
for Antd forms are async and are being run after the onChange
that you have written. To get over this, you can simply add a setTimeout
to the setFieldsValue
:
onChange={e => {
const value = e.target.value;
const { setFieldsValue, getFieldValue } = this.props.form;
setTimeout(() => {
setFieldsValue({
drivers: `+1 - ${value}`
});
}, 0);
}}
A more pragmatic way to do this, would be to use the normalize
function of getFieldDecorator
:
{getFieldDecorator(`drivers`, {
initialValue: "",
normalize: (value) => {
return `+1 ${value}`;
}
})}
However, this would add +1
on every change and that doesn't look like what you would want to do. So alternatively:
normalize: (value) => {
if(!value.startsWith('+1')) {
return `+1 ${value}`;
}
return value;
}
Codesandbox
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With