how to implement form for mapped child component

I have a parent component that has the root <Form>. The child component has another fields which needs to be validated. But the the child component is mapped from a data and once i try to change one field, it changes every fields.

Code:

  <Form id="myForm" name="basic" onFinish={onSubmit}>
    <Form.Item
      name="title"
      rules={[
        {
          required: true,
          message: "Please input your title!"
        }
      ]}
    >
      <Text editable>{title}</Text>
    </Form.Item>
    {data.map((d) => (
      <SecForm />
    ))}
  </Form>

Child Component:

const SecForm = () => {
  return (
    <>
      <Form.Item
        label="target"
        name="target"
        rules={[
          {
            required: true,
            message: "Please input your target!"
          }
        ]}
      >
        <Input placeholder="Target" />
      </Form.Item>
    </>
  );
};

Tried giving ids to the mapped component, but still dint work.
Any simpler solution is apreciated.

Code sandbox link: https://codesandbox.io/s/basic-antd-4-16-9-forked-o8nxdl?file=/index.js

>Solution :

I believe this happens because <SecForm> sets the same name to all form items. Try to pass the data to that component, and change the name of the item based on it

const SecForm = ({ data }) => {
  return (
   <>
      <Form.Item
        label="target"
        name={`target${data}`}
        rules={[
          {
            required: true,
            message: "Please input your target!"
          }
        ]}
      >
        <Input placeholder="Target" />
      </Form.Item>
     </>

);
};

Leave a Reply