Skip to content

Commit 0bd1922

Browse files
committed
feat: add prop preventDefault in toggle component
1 parent 5675c1f commit 0bd1922

File tree

1 file changed

+20
-8
lines changed

1 file changed

+20
-8
lines changed

src/Common/Toggle/Toggle.tsx

Lines changed: 20 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
* limitations under the License.
1515
*/
1616

17-
import React, { useCallback } from 'react'
17+
import React, { SyntheticEvent, useCallback } from 'react'
1818
import { throttle, useEffectAfterMount } from '../Helper'
1919
import './Toggle.scss'
2020

@@ -28,6 +28,7 @@ const Toggle = ({
2828
Icon = null,
2929
iconClass = '',
3030
throttleOnChange = false,
31+
preventDefaultOnLabel = false,
3132
...props
3233
}) => {
3334
const [active, setActive] = React.useState(selected)
@@ -44,26 +45,37 @@ const Toggle = ({
4445
setActive(selected)
4546
}, [selected])
4647

47-
function handleClick(e) {
48+
function handleClick() {
4849
if (!disabled) {
4950
setActive((active) => !active)
5051
}
5152
}
5253

5354
const throttledHandleClick = useCallback(throttle(handleClick, 500), [disabled])
5455

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+
5571
return (
5672
<label
5773
{...props}
5874
className={`${rootClassName} toggle__switch ${disabled ? 'disabled' : ''}`}
5975
style={{ ['--color' as any]: color }}
76+
onClick={handleLabelClick}
6077
>
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" />
6779
<span className={`toggle__slider ${Icon ? 'with-icon br-4 dc__border' : 'round'}`} data-testid={dataTestId}>
6880
{Icon && <Icon className={`icon-dim-20 br-4 p-2 ${iconClass}`} />}
6981
</span>

0 commit comments

Comments
 (0)