skip to Main Content

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


  1. I think you should use map instead of forEach as forEach doesn’t return anything.

    Login or Signup to reply.
  2. Yes, it’s better to use map() method if you are writing to ES6. But you can continue to use the forEach() method. Use the keys property instead of entries. It goes like this:

    {Object.keys(data).forEach((key, value) => {
        <Form.Item label={key} name={key}>
          <Input value={value} />
        </Form.Item>;
    })}
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search