test.js 2.23 KB
import React, { useState } from 'react';
import { Formik, Form, Field, FieldArray } from 'formik';

const AccordionForm = () => {
  const [expandedIndex, setExpandedIndex] = useState(0); // Initially set the first item as expanded

  const toggleAccordion = (index) => {
    setExpandedIndex((prevIndex) => (prevIndex === index ? null : index));
  };

  return (
    <div>
      <Formik
        initialValues={{
          items: [{ title: '', content: '' }]
        }}
        onSubmit={(values) => {
          console.log(values);
        }}
      >
        {({ values }) => (
          <Form>
            <FieldArray name="items">
              {({ push, remove }) => (
                <div>
                  {values.items.map((_, index) => (
                    <div key={index}>
                      <AccordionItem
                        index={index}
                        expanded={expandedIndex === index}
                        toggleAccordion={() => toggleAccordion(index)}
                        remove={() => remove(index)}
                      >
                        <div>
                          <Field name={`items.${index}.title`} placeholder="Title" />
                          <Field name={`items.${index}.content`} placeholder="Content" />
                        </div>
                      </AccordionItem>
                    </div>
                  ))}
                  <button
                    type="button"
                    onClick={() => {
                      push({ title: '', content: '' });
                      setExpandedIndex(values.items.length);
                    }}
                  >
                    Add Item
                  </button>
                </div>
              )}
            </FieldArray>
            <button type="submit">Submit</button>
          </Form>
        )}
      </Formik>
    </div>
  );
};

const AccordionItem = ({ index, expanded, toggleAccordion, remove, children }) => {
  return (
    <div>
      <button type="button" onClick={toggleAccordion}>
        {expanded ? '-' : '+'}
      </button>
      <button type="button" onClick={remove}>Remove</button>
      <div style={{ display: expanded ? 'block' : 'none' }}>{children}</div>
    </div>
  );
};

export default AccordionForm;