Creating a custom hook for handling keyboard shortcuts in React involves using the useEffect
hook to attach event listeners for key presses and cleaning up those listeners when the component unmounts. Here's a simple example of a custom hook for handling keyboard shortcuts:
jsximport { useEffect, useRef } from 'react';
const useKeyboardShortcut = (targetKey, callback) => {
const callbackRef = useRef(callback);
useEffect(() => {
callbackRef.current = callback;
}, [callback]);
useEffect(() => {
const handleKeyPress = (event) => {
if (event.key === targetKey) {
callbackRef.current();
}
};
window.addEventListener('keydown', handleKeyPress);
return () => {
window.removeEventListener('keydown', handleKeyPress);
};
}, [targetKey]);
};
export default useKeyboardShortcut;
Here's how you can use this custom hook in your component:
jsximport React from 'react';
import useKeyboardShortcut from './useKeyboardShortcut'; // adjust the path based on your project structure
const MyComponent = () => {
const handleShortcut = () => {
// Your logic for handling the shortcut goes here
console.log('Shortcut pressed!');
};
// Register 'A' as the target key for the shortcut
useKeyboardShortcut('A', handleShortcut);
return (
<div>
{/* Your component content */}
</div>
);
};
export default MyComponent;
In this example, the useKeyboardShortcut
hook takes two parameters: targetKey
and callback
. It sets up a keydown
event listener on the window
object and checks if the pressed key matches the targetKey
. If there's a match, it invokes the provided callback
function.
Remember to clean up the event listener when the component unmounts to avoid memory leaks. The cleanup is done in the return
statement of the useEffect
hook.
You can customize this hook further based on your needs, such as supporting multiple keys, handling key combinations, or adding more sophisticated logic within the callback function.