Skip to content

Commit 0076155

Browse files
Ricardo Lüdersrluders
Ricardo Lüders
authored andcommitted
fix(toggleswitch): fix state and replace onkeypress with onkeyup
This commit fixes the state for disable + enabled ToggleSwitch and also replaces the deprecated onKeyPress with onKeyDown fix themesberg#986
1 parent e62e02d commit 0076155

File tree

1 file changed

+9
-6
lines changed

1 file changed

+9
-6
lines changed

src/components/ToggleSwitch/ToggleSwitch.tsx

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import type { ComponentProps, FC, KeyboardEvent, MouseEvent } from 'react';
2-
import { useId } from 'react';
2+
import { useId, useRef } from 'react';
33
import { twMerge } from 'tailwind-merge';
44
import type { DeepPartial, FlowbiteBoolean, FlowbiteColors } from '../../';
55
import { useTheme } from '../../';
@@ -44,16 +44,18 @@ export const ToggleSwitch: FC<ToggleSwitchProps> = ({
4444
}) => {
4545
const id = useId();
4646
const theme = mergeDeep(useTheme().theme.toggleSwitch, customTheme);
47+
const buttonRef = useRef<HTMLButtonElement>(null);
4748

4849
const toggle = (): void => onChange(!checked);
4950

5051
const handleClick = (event: MouseEvent<HTMLButtonElement>): void => {
51-
event.preventDefault();
5252
toggle();
5353
};
5454

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+
}
5759
};
5860

5961
return (
@@ -62,12 +64,13 @@ export const ToggleSwitch: FC<ToggleSwitchProps> = ({
6264
<input checked={checked} hidden name={name} readOnly type="checkbox" className="sr-only" />
6365
) : null}
6466
<button
67+
ref={buttonRef}
6568
aria-checked={checked}
6669
aria-labelledby={`${id}-flowbite-toggleswitch-label`}
6770
disabled={disabled}
6871
id={`${id}-flowbite-toggleswitch`}
6972
onClick={handleClick}
70-
onKeyPress={handleKeyPress}
73+
onKeyDown={handleOnKeyDown}
7174
role="switch"
7275
tabIndex={0}
7376
type="button"
@@ -79,7 +82,7 @@ export const ToggleSwitch: FC<ToggleSwitchProps> = ({
7982
className={twMerge(
8083
theme.toggle.base,
8184
theme.toggle.checked[checked ? 'on' : 'off'],
82-
!disabled && checked && theme.toggle.checked.color[color],
85+
checked && theme.toggle.checked.color[color],
8386
)}
8487
/>
8588
{label?.length ? (

0 commit comments

Comments
 (0)