1
1
import type { ComponentProps , FC , KeyboardEvent , MouseEvent } from 'react' ;
2
- import { useId } from 'react' ;
2
+ import { useId , useRef } from 'react' ;
3
3
import { twMerge } from 'tailwind-merge' ;
4
4
import type { DeepPartial , FlowbiteBoolean , FlowbiteColors } from '../../' ;
5
5
import { useTheme } from '../../' ;
@@ -44,16 +44,18 @@ export const ToggleSwitch: FC<ToggleSwitchProps> = ({
44
44
} ) => {
45
45
const id = useId ( ) ;
46
46
const theme = mergeDeep ( useTheme ( ) . theme . toggleSwitch , customTheme ) ;
47
+ const buttonRef = useRef < HTMLButtonElement > ( null ) ;
47
48
48
49
const toggle = ( ) : void => onChange ( ! checked ) ;
49
50
50
51
const handleClick = ( event : MouseEvent < HTMLButtonElement > ) : void => {
51
- event . preventDefault ( ) ;
52
52
toggle ( ) ;
53
53
} ;
54
54
55
- const handleKeyPress = ( event : KeyboardEvent < HTMLButtonElement > ) : void => {
56
- event . preventDefault ( ) ;
55
+ const handleOnKeyDown = ( event : KeyboardEvent < HTMLButtonElement > ) : void => {
56
+ if ( event . code == 'Enter' ) {
57
+ event . preventDefault ( ) ;
58
+ }
57
59
} ;
58
60
59
61
return (
@@ -62,12 +64,13 @@ export const ToggleSwitch: FC<ToggleSwitchProps> = ({
62
64
< input checked = { checked } hidden name = { name } readOnly type = "checkbox" className = "sr-only" />
63
65
) : null }
64
66
< button
67
+ ref = { buttonRef }
65
68
aria-checked = { checked }
66
69
aria-labelledby = { `${ id } -flowbite-toggleswitch-label` }
67
70
disabled = { disabled }
68
71
id = { `${ id } -flowbite-toggleswitch` }
69
72
onClick = { handleClick }
70
- onKeyPress = { handleKeyPress }
73
+ onKeyDown = { handleOnKeyDown }
71
74
role = "switch"
72
75
tabIndex = { 0 }
73
76
type = "button"
@@ -79,7 +82,7 @@ export const ToggleSwitch: FC<ToggleSwitchProps> = ({
79
82
className = { twMerge (
80
83
theme . toggle . base ,
81
84
theme . toggle . checked [ checked ? 'on' : 'off' ] ,
82
- ! disabled && checked && theme . toggle . checked . color [ color ] ,
85
+ checked && theme . toggle . checked . color [ color ] ,
83
86
) }
84
87
/>
85
88
{ label ?. length ? (
0 commit comments