|
1 | 1 | ```tsx |
2 | 2 | import React, { useRef, useState } from 'react'; |
3 | | -import { IonToggle, IonButton, ToggleCustomEvent } from '@ionic/react'; |
| 3 | +import { IonToggle, ToggleCustomEvent } from '@ionic/react'; |
4 | 4 |
|
5 | 5 | function Example() { |
| 6 | + const wifiRef = useRef<HTMLIonToggleElement>(null); |
| 7 | + |
6 | 8 | const [isTouched, setIsTouched] = useState<boolean>(false); |
7 | 9 | const [isValid, setIsValid] = useState<boolean | undefined>(); |
8 | | - |
9 | | - const wifiRef = useRef<HTMLIonToggleElement>(null); |
| 10 | + const [isChecked, setIsChecked] = useState<boolean>(true); |
10 | 11 |
|
11 | 12 | const validateToggle = (event: ToggleCustomEvent<{ checked: boolean }>) => { |
12 | 13 | setIsTouched(true); |
| 14 | + setIsChecked(event.detail.checked); |
13 | 15 | setIsValid(event.detail.checked); |
14 | 16 | }; |
15 | 17 |
|
16 | | - const submit = (event: React.FormEvent<HTMLFormElement>) => { |
17 | | - event.preventDefault(); |
18 | | - |
19 | | - if (wifiRef.current) { |
20 | | - validateToggle({ detail: { checked: wifiRef.current.checked } } as ToggleCustomEvent<{ |
21 | | - checked: boolean; |
22 | | - }>); |
23 | | - } |
24 | | - }; |
25 | | - |
26 | 18 | return ( |
27 | 19 | <> |
28 | | - <form onSubmit={submit}> |
29 | | - <IonToggle |
30 | | - ref={wifiRef} |
31 | | - className={`${isValid ? 'ion-valid' : ''} ${isValid === false ? 'ion-invalid' : ''} ${ |
32 | | - isTouched ? 'ion-touched' : '' |
33 | | - }`} |
34 | | - helperText="This needs to be enabled" |
35 | | - errorText="This field is required" |
36 | | - onIonChange={(event) => validateToggle(event)} |
37 | | - > |
38 | | - I agree to the terms and conditions |
39 | | - </IonToggle> |
40 | | - |
41 | | - <br /> |
42 | | - |
43 | | - <IonButton type="submit" size="small"> |
44 | | - Submit |
45 | | - </IonButton> |
46 | | - </form> |
| 20 | + <IonToggle |
| 21 | + ref={wifiRef} |
| 22 | + className={`${isValid ? 'ion-valid' : ''} ${ |
| 23 | + isValid === false ? 'ion-invalid' : '' |
| 24 | + } ${isTouched ? 'ion-touched' : ''}`} |
| 25 | + helperText="Enable to connect to available networks" |
| 26 | + errorText="Must be enabled to access the internet" |
| 27 | + justify="space-between" |
| 28 | + checked={isChecked} |
| 29 | + onIonChange={(event) => validateToggle(event)} |
| 30 | + > |
| 31 | + I agree to the terms and conditions |
| 32 | + </IonToggle> |
47 | 33 | </> |
48 | 34 | ); |
49 | 35 | } |
|
0 commit comments