14
14
* limitations under the License.
15
15
*/
16
16
17
- import React , { useCallback } from 'react'
17
+ import React , { SyntheticEvent , useCallback } from 'react'
18
18
import { throttle , useEffectAfterMount } from '../Helper'
19
19
import './Toggle.scss'
20
20
@@ -28,6 +28,7 @@ const Toggle = ({
28
28
Icon = null ,
29
29
iconClass = '' ,
30
30
throttleOnChange = false ,
31
+ preventDefaultOnLabel = false ,
31
32
...props
32
33
} ) => {
33
34
const [ active , setActive ] = React . useState ( selected )
@@ -44,26 +45,37 @@ const Toggle = ({
44
45
setActive ( selected )
45
46
} , [ selected ] )
46
47
47
- function handleClick ( e ) {
48
+ function handleClick ( ) {
48
49
if ( ! disabled ) {
49
50
setActive ( ( active ) => ! active )
50
51
}
51
52
}
52
53
53
54
const throttledHandleClick = useCallback ( throttle ( handleClick , 500 ) , [ disabled ] )
54
55
56
+ const handleChange = ( ) => {
57
+ if ( throttleOnChange ) {
58
+ throttledHandleClick ( )
59
+ return
60
+ }
61
+ handleClick ( )
62
+ }
63
+
64
+ const handleLabelClick = ( e : SyntheticEvent ) => {
65
+ if ( preventDefaultOnLabel ) {
66
+ e . preventDefault ( )
67
+ handleChange ( )
68
+ }
69
+ }
70
+
55
71
return (
56
72
< label
57
73
{ ...props }
58
74
className = { `${ rootClassName } toggle__switch ${ disabled ? 'disabled' : '' } ` }
59
75
style = { { [ '--color' as any ] : color } }
76
+ onClick = { handleLabelClick }
60
77
>
61
- < input
62
- type = "checkbox"
63
- checked = { ! ! active }
64
- onChange = { throttleOnChange ? throttledHandleClick : handleClick }
65
- className = "toggle__input"
66
- />
78
+ < input type = "checkbox" checked = { ! ! active } onChange = { handleChange } className = "toggle__input" />
67
79
< span className = { `toggle__slider ${ Icon ? 'with-icon br-4 dc__border' : 'round' } ` } data-testid = { dataTestId } >
68
80
{ Icon && < Icon className = { `icon-dim-20 br-4 p-2 ${ iconClass } ` } /> }
69
81
</ span >
0 commit comments