Skip to content

Commit

Permalink
feat: a custom hook to listen to key presses (#391)
Browse files Browse the repository at this point in the history
* feat: a custom hook to listen to key presses

* chore: changed useKeyPress to a more aproprietade folder

* feat: add tests for useKeyPress

* refactor: reducing redundancies in code
  • Loading branch information
leandrokzu authored Feb 20, 2024
1 parent 575ca50 commit bd3bc1f
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
35 changes: 35 additions & 0 deletions src/hooks/useKeyPress/useKeyPress.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { act, renderHook } from '@testing-library/react';

import useKeyPress from './useKeyPress';

describe('useKeyPress', () => {
let action: (event: KeyboardEvent) => void;
let targetKey: string;

beforeEach(() => {
action = vi.fn();
targetKey = 'Enter';
});

it('calls action function when target key is pressed', () => {
renderHook(() => useKeyPress(targetKey, action));

act(() => {
const event = new KeyboardEvent('keydown', { key: targetKey });
window.dispatchEvent(event);
});

expect(action).toHaveBeenCalled();
});

it('does not call action function when a different key is pressed', () => {
renderHook(() => useKeyPress(targetKey, action));

act(() => {
const event = new KeyboardEvent('keydown', { key: 'Escape' });
window.dispatchEvent(event);
});

expect(action).not.toHaveBeenCalled();
});
});
19 changes: 19 additions & 0 deletions src/hooks/useKeyPress/useKeyPress.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { useEffect } from 'react';

function useKeyPress(
targetKey: string,
action: (event: KeyboardEvent) => void
): void {
const downHandler = (event: KeyboardEvent) => {
if (event.key === targetKey) action(event);
};

useEffect(() => {
window.addEventListener('keydown', downHandler);
return () => {
window.removeEventListener('keydown', downHandler);
};
}, []);
}

export default useKeyPress;

0 comments on commit bd3bc1f

Please sign in to comment.