Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
     </>

);
};

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading