How to use setFieldValue and pass the value as props between components
29,217
Solution 1
fname
is not defined in getFieldDecorator
.
You should do this:
handleChange = (e) => {
const fname = e.target.name;
const fvalue = e.target.value;
this.props.form.setFieldsValue({
[fname]: fvalue
});
}
Solution 2
You can create your own function to do this:
export const setFieldValue = (
form: FormInstance,
name: NamePath,
value: string
): void => {
if (form && form.getFieldValue(name)) {
const fixname: string[] = [];
if (typeof name == 'object') {
name.forEach((node: string) => {
fixname.push(node);
});
} else {
fixname.push(String(name));
}
let fieldsValue: unknown;
fixname.reverse().forEach((node: string) => {
fieldsValue = {
[String(node)]: fieldsValue != undefined ? fieldsValue : value,
};
});
form.setFieldsValue(fieldsValue);
}
};
and you can use like that
setFieldValue(form, 'phone', '1111111111');
or
setFieldValue(form, ['phones', 'mobile'], '2222222222');
Author by
Shibu
Updated on May 23, 2021Comments
-
Shibu about 3 years
I'm trying to use ant design forms in my sample registration form, when i'm trying to use setFieldsValue it throws error as "Cannot use setFieldsValue unless getFieldDecorator is used". But I had already used getFieldDecorator in my code.Here is a sample of my code.
handleChange = (e) => { const fname = e.target.name; const fvalue = e.target.value; this.props.setFieldsValue({ fname: fvalue }); } render(){ const { getFieldDecorator } = this.props.form return ( <Row gutter={4}> <Col className="reg-personal-details-grid-column" span={24}> <FormItem {...formItemLayout} label="First Name"> {getFieldDecorator("firstName", { rules: [ { required: true } ] })( <Input placeholder="First Name" required name="firstName" onChange={this.handleChange} /> )} </FormItem> </Col> </Row> ) }
-
Shibu about 6 yearsThanks you... Was my mistake in declaring the fname where the setFields function took it as a string?
-
Sunil Kumar Singh over 4 years@Shibu yes when you refer variable name inside setFieldsValue it takes as string and that created your problem