-
Notifications
You must be signed in to change notification settings - Fork 102
/
Copy pathFormhandling.mdx.outdated
371 lines (329 loc) · 11.9 KB
/
Formhandling.mdx.outdated
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
import { Meta, Markdown } from '@storybook/blocks';
import { RegisterForm } from './knowledgeBaseExamples/formExamples';
import { Footer, TableOfContent } from '@sb/components';
[//]: # 'TODO: update this entry to be compatible with Form v2'
<Meta title="Knowledge Base/Form Handling" />
# Form Handling
This guide demonstrates the use of the `Form` component.
## Simple UI5 Web Components for React Form
This Form is implemented with the `Form` component from UI5 Web Components for React.
The children of the `Form` should only be `FormGroup` and `FormItem` in order to preserve the intended design. The children of `FormGroup` should only be `FormItem` and the children of `FormItem` can be an arbitrary React Node.
You can then create a form with UI5 Web Components for React as follows. Also, you can find this example in a Codesandbox.
[](https://codesandbox.io/p/sandbox/wcr-form-forked-9f5br7?file=%2Fsrc%2FApp.js)
<details>
<summary>Show code</summary>
```jsx
import { useState } from 'react';
import {
ThemeProvider,
Form,
FormGroup,
FormItem,
Input,
Option,
Select,
CheckBox,
Button,
MultiComboBox,
MultiComboBoxItem,
DatePicker,
Label
} from '@ui5/webcomponents-react';
import ButtonType from '@ui5/webcomponents/dist/types/ButtonType.js';
import InputType from '@ui5/webcomponents/dist/types/InputType.js';
export default function RegisterForm() {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [country, setCountry] = useState('Germany');
const [birthday, setBirthday] = useState('');
const [payment, setPayment] = useState([]);
const handleSubmit = (e) => {
const values = {
email: email,
password: password,
country: country,
birthday: birthday,
payment: payment
};
alert(JSON.stringify(values, null, 2));
console.log(values);
//prevent page reload
e.preventDefault();
};
const handleEmailInput = (e) => {
setEmail(e.target.value);
};
const handlePasswordInput = (e) => {
setPassword(e.target.value);
};
const handleCountryChange = (e) => {
setCountry(e.detail.selectedOption.innerText);
};
const handleBirthdayChange = (e) => {
setBirthday(e.detail.value);
};
const handlePaymentSelectionChange = (e) => {
const selected = Object.values(e.detail.items).map((val) => val.text);
setPayment(selected);
};
return (
<ThemeProvider>
<Form onSubmit={handleSubmit}>
<FormGroup titleText="Create Account">
<FormItem label={<Label required>Email</Label>}>
<Input name="email" required type={InputType.Email} value={email} onInput={handleEmailInput} />
</FormItem>
<FormItem label={<Label required>Password</Label>}>
<Input name="password" required type={InputType.Password} value={password} onInput={handlePasswordInput} />
</FormItem>
<FormItem label="Country">
<Select name="country" onChange={handleCountryChange}>
<Option>Germany</Option>
<Option>France</Option>
<Option>Italy</Option>
</Select>
</FormItem>
<FormItem label="Date of Birth">
<DatePicker value={birthday} onChange={handleBirthdayChange}></DatePicker>
</FormItem>
<FormItem label="Payment methods">
<MultiComboBox onSelectionChange={handlePaymentSelectionChange}>
<MultiComboBoxItem text="Credit card" />
<MultiComboBoxItem text="PayPal" />
<MultiComboBoxItem text="Bank transfer" />
</MultiComboBox>
</FormItem>
<FormItem>
<Button type={ButtonType.Submit}>Submit</Button>
</FormItem>
</FormGroup>
</Form>
</ThemeProvider>
);
}
```
</details>
Now the `RegisterForm` would compile to this:
<RegisterForm />
Whenever a component has a custom event (e.g. onChange event from `DatePicker`), the corresponding value should be fetched via event.detail (not event.target). This will give you the correct updated value since the internal input has already been updated. At the time the event is fired, however, it is not yet updated and therefore event.target might also not be updated yet.
By default, the browser will reload the page when a form submission event is triggered. Generally, you want to avoid this in React applications because it would cause you to lose the state.
To prevent the default browser behavior, you have to use `e.preventDefault()` in the `onSubmit` event.
## UI5 Web Components for React Form with React Hook Form State Management and Zod Validation
- [React Hook Form](https://github.com/react-hook-form/react-hook-form): form state management and validation
- [Zod](https://github.com/colinhacks/zod): schema validation with static type inference
Input components from UI5 Web Components for React can be used with external libraries like "React Hook Form" and "Zod".
Some components like the `Input` **should** work out of the box (depending on how the library handles properties and events), but for others, such as those that implement `CustomEvent`s or custom properties for `value` handling, some customization are required to ensure the correct state is passed to the form library.
Here you can find a codeSandbox example that shows the use of various input components from UI5 Web Components for React together with "React Hook Form" and "Zod".
[](https://codesandbox.io/p/sandbox/kind-ben-7c5xcr?file=%2Fsrc%2FApp.tsx)
<details>
<summary>Show Code</summary>
```jsx
import {
ThemeProvider,
Form,
FormGroup,
FormItem,
Label,
Input,
Select,
Button,
MultiComboBox,
DatePicker,
CheckBox,
Popover,
Option,
MultiComboBoxItem,
ObjectStatus
} from '@ui5/webcomponents-react';
import ButtonType from '@ui5/webcomponents/dist/types/ButtonType.js';
import InputType from '@ui5/webcomponents/dist/types/InputType.js';
import ValueState from '@ui5/webcomponents-base/dist/types/ValueState.js';
import { useForm, useController } from 'react-hook-form';
import { z } from 'zod';
import { zodResolver } from '@hookform/resolvers/zod';
import { createPortal } from 'react-dom';
import { useEffect, useId, useState } from 'react';
// Zod schema
const schema = z
.object({
email: z.string().email(),
password: z
.string()
.regex(/[A-Z]/, { message: 'Must contain at least one capital letter' })
.min(8, { message: 'Must be 8 or more characters long' }),
confirmPassword: z
.string()
.regex(/[A-Z]/, { message: 'Must contain at least one capital letter' })
.min(8, { message: 'Must be 8 or more characters long' }),
toc: z.literal(true, {
errorMap: () => ({ message: 'Please accept the terms of service' })
}),
country: z.string(),
dob: z.string(),
payment: z.any()
})
.superRefine(({ confirmPassword, password }, ctx) => {
if (confirmPassword !== password) {
ctx.addIssue({
code: 'custom',
message: 'The passwords did not match',
path: ['confirmPassword']
});
}
});
/* ***********************
To ensure the correct behavior of individual components in conjunction with the "React Hook Form", they must be "wrapped".
Basically, this applies to all components that use custom events or properties.
*********************** */
const WrappedSelect = (props) => {
const { field } = useController(props);
const handleChange = (e) => {
field.onChange(e.detail.selectedOption.textContent);
};
return (
<Select {...field} onChange={handleChange}>
<Option>Germany</Option>
<Option>France</Option>
<Option>Italy</Option>
</Select>
);
};
const WrappedMultiComboBox = (props) => {
const { field } = useController(props);
const handleChange = (e) => {
field.onChange(Object.values(e.detail.items).map((val) => val.text));
};
return (
<MultiComboBox {...field} onSelectionChange={handleChange}>
<MultiComboBoxItem text="Credit card" />
<MultiComboBoxItem text="PayPal" />
<MultiComboBoxItem text="Bank transfer" />
</MultiComboBox>
);
};
const WrappedCheckBox = (props) => {
const { field, formState } = useController(props);
const [open, setOpen] = useState(false);
const errorMessage = formState.errors?.[field.name]?.message;
const uniqueId = useId();
const handleChange = (e) => {
field.onChange(e.target.checked);
};
const handleFocus = (e) => {
if (errorMessage) {
setOpen(true);
}
};
const handleClose = () => {
setOpen(false);
};
useEffect(() => {
if (!errorMessage) {
setOpen(false);
}
}, [errorMessage]);
return (
<>
<CheckBox
{...field}
checked={field.value}
onChange={handleChange}
id={uniqueId}
onFocus={handleFocus}
valueState={errorMessage ? ValueState.Negative : ValueState.None}
/>
{createPortal(
<Popover open={open} opener={uniqueId} onClose={handleClose} initialFocus={uniqueId}>
<ObjectStatus state={ValueState.Negative}>{errorMessage}</ObjectStatus>
</Popover>,
document.body
)}
</>
);
};
function App() {
const {
handleSubmit,
register,
control,
formState: { errors }
} = useForm({
defaultValues: {
email: '',
password: '',
confirmPassword: '',
country: 'Germany',
dob: '',
payment: [],
toc: false
},
mode: 'onChange',
resolver: zodResolver(schema)
});
const onSubmit = (data) => {
alert(JSON.stringify(data, null, 2));
console.log(data);
};
return (
<ThemeProvider>
<Form onSubmit={handleSubmit(onSubmit)} labelSpanM={4}>
<FormGroup titleText="Create Account">
<FormItem label={<Label required>Email</Label>}>
<Input
{...register('email', { required: true })}
valueState={errors.email ? ValueState.Negative : ValueState.None}
valueStateMessage={<span>{errors.email?.message}</span>}
type={InputType.Email}
/>
</FormItem>
<FormItem label={<Label required>Password</Label>}>
<Input
{...register('password', { required: true })}
valueState={errors.password ? ValueState.Negative : ValueState.None}
valueStateMessage={<span>{errors.password?.message}</span>}
type={InputType.Password}
/>
</FormItem>
<FormItem label={<Label required>Confirm Password</Label>}>
<Input
{...register('confirmPassword', { required: true })}
valueState={errors.confirmPassword ? ValueState.Negative : ValueState.None}
valueStateMessage={<span>{errors.confirmPassword?.message}</span>}
type={InputType.Password}
/>
</FormItem>
<FormItem label="Country">
<WrappedSelect name="country" control={control} />
</FormItem>
<FormItem label="Date of Birth">
<DatePicker {...register('dob')} />
</FormItem>
<FormItem label="Payment methods">
<WrappedMultiComboBox name="payment" control={control} />
</FormItem>
<FormItem
label={
<Label style={{ alignSelf: 'start', paddingTop: '0.75rem' }} required>
I accept the terms of service
</Label>
}
>
<WrappedCheckBox
name="toc"
control={control}
rules={{ required: true }}
valueState={errors.toc ? ValueState.Negative : ValueState.None}
/>
</FormItem>
</FormGroup>
<FormItem>
<Button type={ButtonType.Submit}>Submit</Button>
</FormItem>
</Form>
</ThemeProvider>
);
}
export default App;
```
</details>
<Footer />