Blame view

pages/test.js 2.23 KB
1
import React, { useState } from 'react';
Jyotsna committed
2
import { Formik, Form, Field, FieldArray } from 'formik';
3 4

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

Jyotsna committed
7
  const toggleAccordion = (index) => {
8 9 10 11 12 13
    setExpandedIndex((prevIndex) => (prevIndex === index ? null : index));
  };

  return (
    <div>
      <Formik
Jyotsna committed
14 15 16
        initialValues={{
          items: [{ title: '', content: '' }]
        }}
17 18 19 20 21
        onSubmit={(values) => {
          console.log(values);
        }}
      >
        {({ values }) => (
Jyotsna committed
22
          <Form>
23 24
            <FieldArray name="items">
              {({ push, remove }) => (
Jyotsna committed
25
                <div>
26 27
                  {values.items.map((_, index) => (
                    <div key={index}>
Jyotsna committed
28 29 30 31 32
                      <AccordionItem
                        index={index}
                        expanded={expandedIndex === index}
                        toggleAccordion={() => toggleAccordion(index)}
                        remove={() => remove(index)}
33
                      >
Jyotsna committed
34 35 36
                        <div>
                          <Field name={`items.${index}.title`} placeholder="Title" />
                          <Field name={`items.${index}.content`} placeholder="Content" />
37
                        </div>
Jyotsna committed
38
                      </AccordionItem>
39 40
                    </div>
                  ))}
Jyotsna committed
41 42 43 44 45 46 47 48
                  <button
                    type="button"
                    onClick={() => {
                      push({ title: '', content: '' });
                      setExpandedIndex(values.items.length);
                    }}
                  >
                    Add Item
49
                  </button>
Jyotsna committed
50
                </div>
51 52 53
              )}
            </FieldArray>
            <button type="submit">Submit</button>
Jyotsna committed
54
          </Form>
55 56 57 58 59 60
        )}
      </Formik>
    </div>
  );
};

Jyotsna committed
61 62 63 64 65 66 67 68 69 70 71 72 73
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;