@@ -140,12 +140,21 @@ function App() {
140
140
141
141
** Watch in Field Array**
142
142
143
- ``` javascript copy sandbox="https://codesandbox.io/s/watch-with-usefieldarray-e2d64"
143
+ <TabGroup buttonLabels = { [" TS" , " JS" ]} >
144
+
145
+ ``` typescript copy sandbox="https://codesandbox.io/s/watch-with-usefieldarray-z54xwd"
144
146
import * as React from " react"
145
- import { useForm , useFieldArray , ArrayField } from " react-hook-form"
147
+ import { useForm , useFieldArray } from " react-hook-form"
148
+
149
+ type FormValues = {
150
+ test: {
151
+ firstName: string
152
+ lastName: string
153
+ }[]
154
+ }
146
155
147
156
function App() {
148
- const { register , control , handleSubmit , watch } = useForm ()
157
+ const { register, control, handleSubmit, watch } = useForm < FormValues > ()
149
158
const { fields, remove, append } = useFieldArray ({
150
159
name: " test" ,
151
160
control ,
@@ -158,7 +167,19 @@ function App() {
158
167
< form onSubmit = {handleSubmit(onSubmit )}>
159
168
{fields .map ((field , index ) = > {
160
169
return (
161
- < input key= {field .id } {... register (` test[${ index} ].firstName` )} / >
170
+ <div key = {field.id }>
171
+ <input
172
+ defaultValue = {field.firstName }
173
+ {... register (`test .$ {index }.firstName `)}
174
+ />
175
+ <input
176
+ defaultValue = {field.lastName }
177
+ {... register (`test .$ {index }.lastName `)}
178
+ />
179
+ <button type = " button" onClick = {() => remove(index )}>
180
+ Remove
181
+ </button >
182
+ </div >
162
183
)
163
184
})}
164
185
< button
@@ -177,6 +198,57 @@ function App() {
177
198
}
178
199
```
179
200
201
+ ``` javascript copy sandbox="https://codesandbox.io/s/watch-with-usefieldarray-52yy3z"
202
+ import * as React from " react"
203
+ import { useForm , useFieldArray } from " react-hook-form"
204
+
205
+ function App () {
206
+ const { register , control , handleSubmit , watch } = useForm ()
207
+ const { fields , remove , append } = useFieldArray ({
208
+ name: " test" ,
209
+ control,
210
+ })
211
+ const onSubmit = (data ) => console .log (data)
212
+
213
+ console .log (watch (" test" ))
214
+
215
+ return (
216
+ < form onSubmit= {handleSubmit (onSubmit)}>
217
+ {fields .map ((field , index ) => {
218
+ return (
219
+ < div key= {field .id }>
220
+ < input
221
+ defaultValue= {field .firstName }
222
+ {... register (` test.${ index} .firstName` )}
223
+ / >
224
+ < input
225
+ defaultValue= {field .lastName }
226
+ {... register (` test.${ index} .lastName` )}
227
+ / >
228
+ < button type= " button" onClick= {() => remove (index)}>
229
+ Remove
230
+ < / button>
231
+ < / div>
232
+ )
233
+ })}
234
+ < button
235
+ type= " button"
236
+ onClick= {() =>
237
+ append ({
238
+ firstName: " bill" + renderCount,
239
+ lastName: " luo" + renderCount,
240
+ })
241
+ }
242
+ >
243
+ Append
244
+ < / button>
245
+ < / form>
246
+ )
247
+ }
248
+ ```
249
+
250
+ </TabGroup >
251
+
180
252
## Video
181
253
182
254
---
0 commit comments