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.

-
Since you are using Formik, you should consider using formik.org/docs/api/fieldarray for this case .Shyam– Shyam2021-06-08 09:23:06 +00:00Commented Jun 8, 2021 at 9:23
Add a comment
|
1 Answer
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.