From 0709a6795d6468ac7730f71216f3b8d911bb02f3 Mon Sep 17 00:00:00 2001 From: Nikita Dubyk Date: Sat, 23 Dec 2023 11:07:30 +0300 Subject: [PATCH] fix(toggleswitch component): added forwardRef to ToggleSwitch component fix #1078 --- src/components/ToggleSwitch/ToggleSwitch.tsx | 135 ++++++++++--------- 1 file changed, 70 insertions(+), 65 deletions(-) diff --git a/src/components/ToggleSwitch/ToggleSwitch.tsx b/src/components/ToggleSwitch/ToggleSwitch.tsx index b86cb24d8..31a1501c0 100644 --- a/src/components/ToggleSwitch/ToggleSwitch.tsx +++ b/src/components/ToggleSwitch/ToggleSwitch.tsx @@ -1,5 +1,5 @@ -import type { ComponentProps, FC, KeyboardEvent } from 'react'; -import { useId } from 'react'; +import type { ComponentProps, KeyboardEvent } from 'react'; +import { useId, forwardRef } from 'react'; import { twMerge } from 'tailwind-merge'; import { mergeDeep } from '../../helpers/merge-deep'; import { getTheme } from '../../theme-store'; @@ -26,7 +26,7 @@ export interface FlowbiteToggleSwitchToggleTheme { }; } -export type ToggleSwitchProps = Omit, 'onChange'> & { +export type ToggleSwitchProps = Omit, 'onChange' | 'ref'> & { checked: boolean; color?: keyof FlowbiteColors; sizing?: keyof FlowbiteTextInputSizes; @@ -35,72 +35,77 @@ export type ToggleSwitchProps = Omit, 'onChange'> & { theme?: DeepPartial; }; -export const ToggleSwitch: FC = ({ - checked, - className, - color = 'blue', - sizing = 'md', - disabled, - label, - name, - onChange, - theme: customTheme = {}, - ...props -}) => { - const id = useId(); - const theme = mergeDeep(getTheme().toggleSwitch, customTheme); +export const ToggleSwitch = forwardRef( + ( + { + checked, + className, + color = 'blue', + sizing = 'md', + disabled, + label, + name, + onChange, + theme: customTheme = {}, + ...props + }, + ref, + ) => { + const id = useId(); + const theme = mergeDeep(getTheme().toggleSwitch, customTheme); - const toggle = (): void => onChange(!checked); + const toggle = (): void => onChange(!checked); - const handleClick = (): void => { - toggle(); - }; + const handleClick = (): void => { + toggle(); + }; - const handleOnKeyDown = (event: KeyboardEvent): void => { - if (event.code == 'Enter') { - event.preventDefault(); - } - }; + const handleOnKeyDown = (event: KeyboardEvent): void => { + if (event.code == 'Enter') { + event.preventDefault(); + } + }; - return ( - <> - {name && checked ? ( - - ) : null} - - - ); -}; + + + ); + }, +); ToggleSwitch.displayName = 'ToggleSwitch';