Skip to content

Commit

Permalink
fix(checkbox): added onClick prop
Browse files Browse the repository at this point in the history
  • Loading branch information
elias-oxopia committed Jul 12, 2023
1 parent a1da486 commit 3409d10
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 4 deletions.
11 changes: 11 additions & 0 deletions src/components/Checkbox/Checkbox.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,17 @@ describe('Checkbox', () => {
);
});

test('onClick prop', () => {
const onClickFn = jest.fn();
const component = <Checkbox {...defaultProps} onClick={onClickFn} />;
const { getByTestId } = render(component);

const checkboxLabel = getByTestId('checkbox-label-enabled');
fireEvent.click(checkboxLabel);

expect(onClickFn).toHaveBeenCalledTimes(1);
});

test('className prop', () => {
const className = 'center';
const component = <Checkbox {...defaultProps} className={className} />;
Expand Down
21 changes: 17 additions & 4 deletions src/components/Checkbox/Checkbox.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
import React, { ChangeEventHandler, ReactNode, useEffect, useState } from 'react';
import React, {
ChangeEventHandler,
MouseEventHandler,
ReactNode,
useEffect,
useState,
} from 'react';
import classNames from 'classnames';

import checkIcon from './check.svg';
Expand All @@ -10,14 +16,18 @@ interface Props {
name: string;
value?: boolean;
onChange?: ChangeEventHandler<HTMLInputElement>;
onClick?: MouseEventHandler<HTMLButtonElement>;
className?: string;
isDisabled?: boolean;
description?: string;
label: ReactNode;
}

const Checkbox = React.forwardRef<HTMLInputElement, Props>(
({ name, value, onChange, isDisabled = false, className, description, label }: Props, ref) => {
(
{ name, value, onChange, onClick, isDisabled = false, className, description, label }: Props,
ref,
) => {
const [isChecked, setIsChecked] = useState<boolean>(value ?? false);

useEffect(() => {
Expand All @@ -35,7 +45,7 @@ const Checkbox = React.forwardRef<HTMLInputElement, Props>(
className,
);

const onClick = (event: React.ChangeEvent<HTMLInputElement>) => {
const click = (event: React.ChangeEvent<HTMLInputElement>) => {
// Info at https://fb.me/react-event-pooling
event.persist();

Expand All @@ -53,7 +63,10 @@ const Checkbox = React.forwardRef<HTMLInputElement, Props>(
id={name}
name={name}
checked={isChecked}
onChange={onClick}
onChange={click}
onClick={
isDisabled ? undefined : (onClick as MouseEventHandler<HTMLInputElement> | undefined)
}
ref={ref}
data-testid={name && `checkbox-${name}`}
disabled={isDisabled}
Expand Down

0 comments on commit 3409d10

Please sign in to comment.