test.js
2.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
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;