Trying to populate Antd form items from a given key-value type object, with key as label and value as input parameter. I tried the following code, and I also searched online, but it did not work. What can I try next?
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
I think you should use map instead of forEach as forEach doesn’t return anything.
2
You have to use Array.prototype.map and callback function that you pass inside map function has to return a component or jsx element. Don’t forget to write word return. Also in react loops you have to pass unique value among array items to the key prop.
{Object.keys(data).map((key, value) => {
return <Form.Item label={key} name={key} key={key}>
<Input value={value} />
</Form.Item>;
})}
Other option is to use an arrow function without {}. In that case you don’t need to write word return.
{Object.keys(data).map((key, value) => (
<Form.Item label={key} name={key} key={key}>
<Input value={value} />
</Form.Item>;
)}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity:
The best way to pick a key is to use a string that uniquely identifies a list item among its siblings. Most often you would use IDs from your data as keys.
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>;
})}
1
You must use a map instead of foreach because forEach returns nothing, so the form elements are not rendered.
Here is an example :
https://codesandbox.io/p/sandbox/kind-bouman-59l8qc?file=%2Fsrc%2FApp.js