0

I was working on a form , and I want to render same div in "Active Membership" Section when add more button is pressed. User can have several Active membership, so each time user pressed the button same input section will render. I guess for loop can help but it is not working inside jsx codebase. I am using formik for creating the form.
enter image description here

1
  • Since you are using Formik, you should consider using formik.org/docs/api/fieldarray for this case . Commented Jun 8, 2021 at 9:23

1 Answer 1

1

You can easily implement that using <FieldArray />.

<FieldArray /> is a component that helps with common array/list manipulations. You pass it a name property with the path to the key within values that holds the relevant array.

Resource - Official Documentation (https://formik.org/docs/api/fieldarray)

import { Formik, Form, Field, FieldArray } from "formik";
import "./styles.css";

export default function App() {
  return (
    <div>
      <h1>Friend List</h1>
      <Formik initialValues={{ memberships: [] }}> {/* Initialize a membership empty array*/}
        {(props) => (
          <Form>
            <FieldArray name="memberships">
              {({ push, form: { values } }) => (
                <div>
                  {values.memberships &&
                    values.memberships.length > 0 &&
                    values.memberships.map((item, index) => (
                      <div key={index}>
                        <Field
                          name={`memberships.${index}.name`}
                          placeholder="Membership Title"
                        />
                        <Field
                          name={`memberships.${index}.position`}
                          placeholder="Position"
                        />
                        <Field
                          name={`memberships.${index}.join.date`}
                          placeholder="Join Date"
                        />
                      </div> {/* Active Membership section */}
                    ))}
                  <button type="button" onClick={() => push({})}> {/* Create the click handler */}
                    Add More
                  </button>
                </div>
              )}
            </FieldArray>
          </Form>
        )}
      </Formik>
    </div>
  );
}

https://codesandbox.io/s/formik-add-more-ncsw3?file=/src/App.js

Let me know if you need further support.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.