From 2dd973af4c6c6883a50049333f69c3eb8f8aea3a Mon Sep 17 00:00:00 2001 From: Trevor Huey Date: Wed, 21 Jun 2023 07:56:54 -0500 Subject: [PATCH] fix(react): allow onBlur and onFocus to be passed to Checkbox without messing up focus state (#1095) Closes https://github.com/dequelabs/cauldron/issues/1094 --------- Co-authored-by: Jason --- .../__tests__/src/components/Checkbox/index.js | 10 +++++++++- packages/react/src/components/Checkbox/index.tsx | 16 ++++++++++++++-- 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/packages/react/__tests__/src/components/Checkbox/index.js b/packages/react/__tests__/src/components/Checkbox/index.js index de9d31ecd..429a65742 100644 --- a/packages/react/__tests__/src/components/Checkbox/index.js +++ b/packages/react/__tests__/src/components/Checkbox/index.js @@ -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'; @@ -73,15 +74,22 @@ test('handles disabled prop', () => { }); test('handles focus/blur', () => { - const wrapper = mount(); + const onFocus = sinon.spy(); + const onBlur = sinon.spy(); + + const wrapper = mount( + + ); 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 => { diff --git a/packages/react/src/components/Checkbox/index.tsx b/packages/react/src/components/Checkbox/index.tsx index b4da587ec..fa2bf6ba8 100644 --- a/packages/react/src/components/Checkbox/index.tsx +++ b/packages/react/src/components/Checkbox/index.tsx @@ -31,6 +31,8 @@ const Checkbox = forwardRef( checkboxRef, className, onChange, + onFocus, + onBlur, 'aria-describedby': ariaDescribedby, disabled = false, checked = false, @@ -77,8 +79,18 @@ const Checkbox = forwardRef( 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);