-
Notifications
You must be signed in to change notification settings - Fork 0
/
App.tsx
89 lines (84 loc) · 2.53 KB
/
App.tsx
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
import { Formik, Form, Field, FieldArray } from 'formik'
// We're using an empty person as default.
const emptyPerson = {
first: "",
last: "",
age: 21
}
// If you want people added by default, you can use something like below as the initialization value of `people`.
/*
const startingPeople = [{
first: "First Name",
last: "Last Name",
age: 26
}, {
first: "First Name #2",
last: "Last Name #2",
age: 21
}]
*/
function App() {
return (
<Formik
initialValues={{
//people: startingPeople
people: [emptyPerson]
}}
onSubmit={(values) => {
console.log(values)
}}
>
{({ values }) => (
<Form>
<h1>People</h1>
<FieldArray name="people">
{({ push, remove }) => (
<>
{values.people.map((_person, index) => {
// To simplify code, let's build the starting string of our field names for this specific person which is `people[index]`.
const startName = `people[${index.toString()}]`
return (
<div key={`person-${index.toString()}`}>
<h2>Person #{(index + 1).toString()}</h2>
<div>
<label htmlFor={`${startName}.first`}>First Name</label>
<Field name={`${startName}.first`} />
</div>
<div>
<label htmlFor={`${startName}.last`}>Last Name</label>
<Field name={`${startName}.last`} />
</div>
<div>
<label htmlFor={`${startName}.age`}>Age</label>
<Field
type="number"
name={`${startName}.age`}
/>
</div>
<div>
<button
type="button"
onClick={() => remove(index)}
>Remove</button>
</div>
</div>
)
})}
<div>
<button
type="button"
onClick={() => push(emptyPerson)}
>Add Person</button>
</div>
</>
)}
</FieldArray>
<div>
<button type="submit">Add People!</button>
</div>
</Form>
)}
</Formik>
);
}
export default App;