Skip to content

Commit

Permalink
fix(components): prevent double onChange call in Switch component
Browse files Browse the repository at this point in the history
  • Loading branch information
izmy authored and tomasklim committed Jan 28, 2025
1 parent c239a27 commit 5571b02
Showing 1 changed file with 12 additions and 7 deletions.
19 changes: 12 additions & 7 deletions packages/components/src/components/form/Switch/Switch.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import { ReactNode } from 'react';
import { ReactNode, useId } from 'react';

import styled, { css } from 'styled-components';

import { borders, spacingsPx, typography } from '@trezor/theme';
import { getWeakRandomId } from '@trezor/utils';

import {
getInputColor,
Expand Down Expand Up @@ -135,13 +134,22 @@ export const Switch = ({
className,
labelPosition = 'right',
}: SwitchProps) => {
const id = getWeakRandomId(10);
const id = useId();

const handleChange = () => {
if (isDisabled) return;
onChange(!isChecked);
};

const handleContainerClick = (e: React.MouseEvent<HTMLDivElement>) => {
// Prevent handling clicks that originate from the input or label
const target = e.target as HTMLElement;
if (target.tagName === 'INPUT' || target.tagName === 'LABEL') return;

e.preventDefault();
handleChange();
};

return (
<Wrapper $labelPosition={labelPosition} className={className}>
<Container
Expand All @@ -150,10 +158,7 @@ export const Switch = ({
$isChecked={isChecked}
$isDisabled={isDisabled}
$isAlert={isAlert}
onClick={e => {
e.preventDefault();
handleChange();
}}
onClick={handleContainerClick}
data-testid={dataTest}
$isSmall={isSmall}
>
Expand Down

0 comments on commit 5571b02

Please sign in to comment.