test.js
3.12 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
// AccordionForm.js
import React, { useState } from 'react';
import { Formik, FieldArray, Field, ErrorMessage } from 'formik';
import * as Yup from 'yup';
const validationSchema = Yup.object().shape({
items: Yup.array().of(
Yup.object().shape({
title: Yup.string().required('Title is required'),
content: Yup.string().required('Content is required'),
})
),
});
const initialValues = {
items: [{ title: '', content: '' }],
};
const AccordionForm = () => {
const [expandedIndex, setExpandedIndex] = useState(null);
const handleToggleAccordion = (index) => {
setExpandedIndex((prevIndex) => (prevIndex === index ? null : index));
};
return (
<div>
<h1>Accordion Form</h1>
<Formik
initialValues={initialValues}
validationSchema={validationSchema}
onSubmit={(values) => {
console.log(values);
}}
>
{({ values }) => (
<form>
<FieldArray name="items">
{({ push, remove }) => (
<>
{values.items.map((_, index) => (
<div key={index}>
<div
style={{
border: '1px solid #ccc',
padding: '10px',
marginBottom: '10px',
}}
>
<div
style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
}}
onClick={() => handleToggleAccordion(index)}
>
<h3>Accordion {index + 1}</h3>
<button type="button" onClick={() => remove(index)}>
Remove
</button>
</div>
{expandedIndex === index && (
<div>
<div>
<label htmlFor={`items.${index}.title`}>Title</label>
<Field name={`items.${index}.title`} />
<ErrorMessage name={`items.${index}.title`} component="div" />
</div>
<div>
<label htmlFor={`items.${index}.content`}>Content</label>
<Field name={`items.${index}.content`} />
<ErrorMessage name={`items.${index}.content`} component="div" />
</div>
</div>
)}
</div>
</div>
))}
<button type="button" onClick={() => push({ title: '', content: '' })}>
Add Accordion
</button>
</>
)}
</FieldArray>
<button type="submit">Submit</button>
</form>
)}
</Formik>
</div>
);
};
export default AccordionForm;