I have an application where users can add their data in a form with 2 fields. They can add as many fields as they want.
const Demo = () => {
const onFinish = values => {
console.log("Received values of form:", values);
};
const firstDefaultOpen = {
name: 0,
key: 0,
isListField: true,
fieldKey: 0
};
const testHandler = a => {
console.log("result", a.concat(firstDefaultOpen));
return a.concat(firstDefaultOpen);
};
return (
<Form name="dynamic_form_nest_item" onFinish={onFinish} autoComplete="off">
<Form.List name="users">
{(fields, { add, remove }) => {
return (
<div>
{testHandler(fields).map(field => (
<Space
key={field.key}
style={{ display: "flex", marginBottom: 8 }}
align="start"
>
<Form.Item
{...field}
name={[field.name, "first"]}
fieldKey={[field.fieldKey, "first"]}
rules={[{ required: true, message: "Missing first name" }]}
>
<Input placeholder="First Name" />
</Form.Item>
<Form.Item
{...field}
name={[field.name, "last"]}
fieldKey={[field.fieldKey, "last"]}
rules={[{ required: true, message: "Missing last name" }]}
>
<Input placeholder="Last Name" />
</Form.Item>
<MinusCircleOutlined
onClick={() => {
remove(field.name);
}}
/>
</Space>
))}
<Form.Item>
<Button
type="dashed"
onClick={() => {
add();
}}
block
>
<PlusOutlined /> Add field
</Button>
</Form.Item>
</div>
);
}}
</Form.List>
<Form.Item>
<Button type="primary" htmlType="submit">
Submit
</Button>
</Form.Item>
</Form>
);
};
My target is to set a default pair of inputs as opened. Now you can see when you open the application that first name and last name inputs are open as default. This i made with:
const firstDefaultOpen = {
name: 0,
key: 0,
isListField: true,
fieldKey: 0
};
const testHandler = a => {
console.log("result", a.concat(firstDefaultOpen));
return a.concat(firstDefaultOpen);
};
and here i map() the new array:
{testHandler(fields).map(field => (...
The issue is when i click on Add field button, because there when i try to write something in one input also the same text appears on the another. This is happening because when i click on Add field button you can see in the console.log("result", a.concat(firstDefaultOpen));, that 2 objects are with the same values like:
[Object, Object]
0: Object
name: 0
key: 0
isListField: true
fieldKey: 0
1: Object
name: 0
key: 0
isListField: true
fieldKey: 0
Question: How to set the first object with all values 0, and the next values to be higher, and to get something like?:
[Object, Object]
0: Object
name: 0
key: 0
isListField: true
fieldKey: 0
1: Object
name: 1
key: 1
isListField: true
fieldKey: 1
2: Object
name: 2
key: 2
isListField: true
fieldKey: 2
...
demo: https://codesandbox.io/s/hungry-star-nu5ld?file=/index.js:783-819