Trying to populate Antd form items from a given key-value type object, with key as label and value as input parameter. Following code I tried (also searched online), but it did not work, can someone please help me out here?
import { Form, Input } from 'antd';
const onFinish = (values) => {
console.log('Success:', values);
};
const onFinishFailed = (errorInfo) => {
console.log('Failed:', errorInfo);
};
const data = {
fname: 'First',
lname: 'Last',
age: '31'
};
const MyForm = () => (
<>
<h2>My Data</h2>
<Form
onFinish={onFinish}
onFinishFailed={onFinishFailed}
initialValues={data}
>
{Object.entries(data).forEach(([key, value]) => {
<Form.Item label={key} name={key} >
<Input value={value} />
</Form.Item>
})}
</Form>
</>
);
export default MyForm;
Any workaround using react antd is also welcome
2
Answers
I think you should use map instead of forEach as forEach doesn’t return anything.
Yes, it’s better to use
map()
method if you are writing toES6
. But you can continue to use theforEach()
method. Use thekeys
property instead ofentries
. It goes like this: