score:0

Accepted answer

find the below code.

import react from "react";
import { form, field } from "react-final-form";
import arraymutators from "final-form-arrays";
import { fieldarray } from "react-final-form-arrays";

const onsubmit = () => {
  console.log("submitted");
};

const validate = () => {
  // console.log("validated");
};

const myform = () => (
  <form
    onsubmit={onsubmit}
    mutators={{
      // potentially other mutators could be merged here
      ...arraymutators
    }}
    validate={validate}
    render={({ handlesubmit, pristine, invalid }) => (
      <form onsubmit={handlesubmit}>
        <fieldarray name="customers">
          {({ fields }) => (
            <div>
              <button
                type="button"
                onclick={() =>
                  fields.push({ firstname: "", lastname: "", isvisible: true })
                }
              >
                add customer
              </button>
              {fields.map((name, index) => (
                <div key={name}>
                  <a
                    onclick={() =>
                      (fields.value[index].isvisible = !fields.value[index]
                        .isvisible)
                    }
                  >{`cust #${index}`}</a>
                  {fields.value[index].isvisible ? (
                    <div>
                      <div>
                        <field name={`${name}.firstname`} component="input" />
                      </div>
                      <div>
                        <field name={`${name}.lastname`} component="input" />
                      </div>
                    </div>
                  ) : null}
                  <button type="button" onclick={() => fields.remove(index)}>
                    remove
                  </button>
                </div>
              ))}
            </div>
          )}
        </fieldarray>
      </form>
    )}
  />
);

export default myform;

check the codesandbox link here

score:1

in the fields array, you can add one more key isvisible.

it will look like this:

fields = [
    {
        firstname: 'john',
        lastname: 'doe',
        isvisible: true,
    },
    {
        firstname: 'jane',
        lastname: 'doe',
        isvisible: false,
    }
];

now while showing, only render the field when isvisible is true,

<fieldarray name="customer">
  {({ fields }) => (
    fields.map((name, index) => {
      if(name.isvisible){
        return (
          <div key={index}>
            <field name={`${name}.firstname`} />
            <field name={`${name}.lastname`} />
          </div>
      );
    ))
  )}
</fieldarray>

you can control isvisible key by clicking cust # button.


Related Query

More Query from same tag