Reputation: 169
I am using AntD select. When I put select into a separate component, the form does not see the value Tell me why the form does not receive data on submit ?
const SelectCust = () => {
return (
<Select
mode="multiple"
placeholder="Please select favourite colors"
style={{ width: 500 }}
name="select-multiple"
>
<Option value="red">Red</Option>
<Option value="green">Green</Option>
<Option value="blue">Blue</Option>
</Select>
)};
const Demo = () => {
const onFinish = values => {
console.log("Received values of form: ", values); // {custom:undefined}
};
return (
<Form name="validate_other" onFinish={onFinish}>
<Form.Item name="custom" label="Select custom">
<SelectCust />
</Form.Item>
<Form.Item>
<Button type="primary" htmlType="submit">
Submit
</Button>
</Form.Item>
</Form>
)};
Upvotes: 2
Views: 2593
Reputation: 1534
If you wrap <Select>
with <Form.Item>
it works correctly:
const SelectCust = () => {
return (
<Form.Item name="custom" label="Select custom">
<Select
mode="multiple"
placeholder="Please select favourite colors"
style={{ width: 500 }}
name="select-multiple"
>
<Option value="red">Red</Option>
<Option value="green">Green</Option>
<Option value="blue">Blue</Option>
</Select>
</Form.Item>
);
};
Here is updated Demo
component:
const Demo = () => {
const onFinish = values => {
console.log("Received values of form: ", values);
};
return (
<Form name="validate_other" onFinish={onFinish}>
<SelectCust />
<Form.Item
wrapperCol={{
span: 12,
offset: 6
}}
>
<Button type="primary" htmlType="submit">
Submit
</Button>
</Form.Item>
</Form>
);
};
EDIT 1
It seemed wrong to me that wrapping <Select>
with <Form.Item>
solved the problem, so I looked up <Form>
documentation.
Here is updated code:
const SelectCust = props => {
return (
<Select
mode="multiple"
placeholder="Please select favourite colors"
onChange={props.onColorChange}
>
<Option value="red">Red</Option>
<Option value="green">Green</Option>
<Option value="blue">Blue</Option>
</Select>
);
};
const Demo = () => {
const [form] = Form.useForm();
const onFinish = values => console.log(values);
const handleColorChanged = value => {
form.setFieldsValue({ custom: value });
};
return (
<Form name="validate_other" form={form} onFinish={onFinish}>
<Form.Item name="custom" label="Select custom">
<SelectCust onColorChange={handleColorChanged} />
</Form.Item>
<Form.Item
wrapperCol={{
span: 12,
offset: 6
}}
>
<Button type="primary" htmlType="submit">
Submit
</Button>
</Form.Item>
</Form>
);
};
Update has 3 important steps:
const [form] = Form.useForm()
in the beginning of Demo
componenthandleColorChanged
function and pass it as props to SelectCust
. Handler sets form value by calling form.setFieldsValue()
.from
as props to <Form>
componentUpvotes: 4