This repository was archived by the owner on May 19, 2025. It is now read-only.
forked from replayio-public/react-hook-form
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathformStateWithNestedFields.tsx
More file actions
107 lines (102 loc) · 2.65 KB
/
formStateWithNestedFields.tsx
File metadata and controls
107 lines (102 loc) · 2.65 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
95
96
97
98
99
100
101
102
103
104
105
106
107
import React from 'react';
import { useForm, ValidationMode } from 'react-hook-form';
import { useParams } from 'react-router-dom';
let renderCounter = 0;
const FormStateWithNestedFields = () => {
const { mode } = useParams();
const {
register,
handleSubmit,
formState: {
dirtyFields,
isSubmitted,
submitCount,
touchedFields,
isDirty,
isSubmitting,
isSubmitSuccessful,
isValid,
},
reset,
} = useForm<{
left: {
test1: string;
test2: string;
};
right: {
test1: string;
test2: string;
};
}>({
mode: mode as keyof ValidationMode,
defaultValues: {
left: {
test1: '',
test2: '',
},
right: {
test1: '',
test2: '',
},
},
});
renderCounter++;
return (
<form onSubmit={handleSubmit(() => {})}>
<div style={{ display: 'flex' }}>
<div style={{ display: 'flex', flexDirection: 'column' }}>
<h4>Left</h4>
<input
{...register('left.test1', { required: true })}
placeholder="firstName"
/>
<input
{...register('left.test2', { required: true })}
placeholder="lastName"
/>
</div>
<div style={{ display: 'flex', flexDirection: 'column' }}>
<h4>Right</h4>
<input
{...register('right.test1', { required: false })}
placeholder="firstName"
/>
<input
{...register('right.test2', { required: false })}
placeholder="lastName"
/>
</div>
</div>
<div id="state">
{JSON.stringify({
isDirty,
isSubmitted,
submitCount,
isSubmitting,
isSubmitSuccessful,
isValid,
touched: (
Object.keys(touchedFields) as Array<keyof typeof touchedFields>
).flatMap((topLevelKey) =>
Object.keys(touchedFields[topLevelKey] || {}).map(
(nestedKey) => `${topLevelKey}.${nestedKey}`,
),
),
dirty: (
Object.keys(dirtyFields) as Array<keyof typeof touchedFields>
).flatMap((topLevelKey) =>
Object.keys(dirtyFields[topLevelKey] || {}).map(
(nestedKey) => `${topLevelKey}.${nestedKey}`,
),
),
})}
</div>
<button id="submit">Submit</button>
<button type="button" onClick={() => reset()} id="resetForm">
Reset
</button>
<div id="renderCount">{renderCounter}</div>
</form>
);
};
export const formStateWithNestedFields = FormStateWithNestedFields;