Skip to content

Commit

Permalink
fix(react): allow onBlur and onFocus to be passed to Checkbox without…
Browse files Browse the repository at this point in the history
… messing up focus state (#1095)

Closes #1094

---------

Co-authored-by: Jason <[email protected]>
  • Loading branch information
thuey and scurker authored Jun 21, 2023
1 parent 2d2f1f3 commit 2dd973a
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 3 deletions.
10 changes: 9 additions & 1 deletion packages/react/__tests__/src/components/Checkbox/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import React from 'react';
import sinon from 'sinon';
import { mount } from 'enzyme';
import Checkbox from 'src/components/Checkbox';
import axe from '../../../axe';
Expand Down Expand Up @@ -73,15 +74,22 @@ test('handles disabled prop', () => {
});

test('handles focus/blur', () => {
const wrapper = mount(<Checkbox {...defaultProps} />);
const onFocus = sinon.spy();
const onBlur = sinon.spy();

const wrapper = mount(
<Checkbox {...defaultProps} onFocus={onFocus} onBlur={onBlur} />
);

wrapper.find('[type="checkbox"]').simulate('focus');

expect(wrapper.find('.Checkbox__overlay--focused').exists()).toBeTruthy();
expect(onFocus.calledOnce).toBe(true);

wrapper.find('[type="checkbox"]').simulate('blur');

expect(wrapper.find('.Checkbox__overlay--focused').exists()).toBeFalsy();
expect(onBlur.calledOnce).toBe(true);
});

test('call onChange when checked state changes', done => {
Expand Down
16 changes: 14 additions & 2 deletions packages/react/src/components/Checkbox/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ const Checkbox = forwardRef<HTMLInputElement, CheckboxProps>(
checkboxRef,
className,
onChange,
onFocus,
onBlur,
'aria-describedby': ariaDescribedby,
disabled = false,
checked = false,
Expand Down Expand Up @@ -77,8 +79,18 @@ const Checkbox = forwardRef<HTMLInputElement, CheckboxProps>(
type="checkbox"
checked={isChecked}
disabled={disabled}
onFocus={(): void => setFocused(true)}
onBlur={(): void => setFocused(false)}
onFocus={(e): void => {
setFocused(true);
if (typeof onFocus === 'function') {
onFocus(e);
}
}}
onBlur={(e): void => {
setFocused(false);
if (typeof onBlur === 'function') {
onBlur(e);
}
}}
aria-describedby={ariaDescribedbyId}
onChange={(e): void => {
setIsChecked(e.target.checked);
Expand Down

0 comments on commit 2dd973a

Please sign in to comment.