useKeyDown

The useKeyDown hook allows you to capture the event of pressing a specific keyboard key and execute a callback function when the key is pressed. This is especially useful when you want to add keyboard shortcuts or trigger actions based on key presses.

Press or


  • 1
  • 2
  • 3
  • 4

Parameters

typescript
function useKeyDown(
	keyPress: KeyPress,
	callback: () => void,
	options?: KeyDownOptions
): void;
  • keyPress: required - A string representing the code of the key you want to capture. This can be any valid keyboard key, including alphabetic keys, digits, function keys, control keys, arrow keys, and modifier keys.
  • callback: required - A callback function that will be executed when the specified key(s) are pressed. This is where you can define the actions to be performed when the key combination is detected.
  • options: optional - An object containing options to customize the behavior of the hook. The options object can have the following properties:
    • ctrlKey: A boolean value indicating whether the CTRL key needs to be pressed along with the specified key.
    • altKey: A boolean value indicating whether the ALT key needs to be pressed along with the specified key.
    • shiftKey: A boolean value indicating whether the SHIFT key needs to be pressed along with the specified key.

Usage

Import the useKeyDown hook from hookings and use it in your React components:

jsx
import { useKeyDown } from "hookings";
 
useKeyDown("KeyJ", () => {
	console.log("You pressed the 'J' key!");
});

In the first example, we use the useKeyDown hook to capture the event of pressing the J key and log a message when it happens.

jsx
import { useKeyDown } from "hookings";
 
const MyComponent = () => {
	// Call this function when the 'Ctrl + Enter' keys are pressed
	const handleKeyPress = () => {
		// Your logic here...
	};
 
	useKeyDown("Enter", handleKeyPress, { ctrlKey: true });
 
	// Rest of your component code...
};

In the second example, we create a component MyComponent that uses the useKeyDown hook to handle the Ctrl + Enter key combination. When this combination is detected, the handleKeyPress function is called.

⚠️

Be cautious when using useKeyDown with common keys that have built-in behaviors (e.g., Enter, Escape) to avoid unexpected consequences.

Advanced Examples

You can use the useKeyDown hook with multiple keys or with different combinations of modifier keys. For example:

Handling Multiple Key Combinations

You can use the useKeyDown hook to handle multiple key combinations by calling it multiple times with different keyPress values. For example, let's handle both the Ctrl + S and Ctrl + D key combinations:

jsx
import { useKeyDown } from "hookings";
 
const MyComponent = () => {
	const handleSave = () => {
		console.log("Ctrl + S is pressed! Saving the data...");
	};
 
	const handleDelete = () => {
		console.log("Ctrl + D is pressed! Deleting the item...");
	};
 
	// Handle 'Ctrl + S' key combination
	useKeyDown("KeyS", handleSave, { ctrlKey: true });
 
	// Handle 'Ctrl + D' key combination
	useKeyDown("KeyD", handleDelete, { ctrlKey: true });
 
	// Rest of your component code...
};

In this example, when the user presses Ctrl + S, the handleSave function is called, and when Ctrl + D is pressed, the handleDelete function is called.

Triggering Form Submission

You can use the useKeyDown hook to trigger form submission when the user presses the Enter key inside an input field. For example:

jsx
import { useKeyDown } from "hookings";
 
const MyForm = () => {
	const handleSubmit = () => {
		console.log("Form submitted!");
		// Add logic to submit the form data...
	};
 
	// Trigger form submission when the 'Enter' key is pressed inside the input field
	useKeyDown("Enter", handleSubmit);
 
	return (
		<form>
			<input type='text' placeholder='Enter your name' />
			<button type='submit'>Submit</button>
		</form>
	);
};

In this example, when the user focuses on the input field and presses the Enter key, the form will be submitted, and the handleSubmit function will be called.

Handling Arrow Key Navigation

You can use the useKeyDown hook to handle arrow key navigation in your application. For example, let's implement a simple image gallery that allows users to navigate between images using the left and right arrow keys:

jsx
import { useState } from "react";
import { useKeyDown } from "hookings";
 
const ImageGallery = () => {
	const [currentImage, setCurrentImage] = useState(0);
	const images = ["image1.jpg", "image2.jpg", "image3.jpg"];
 
	const handleLeftArrow = () => {
		setCurrentImage((prevImage) =>
			prevImage > 0 ? prevImage - 1 : images.length - 1
		);
	};
 
	const handleRightArrow = () => {
		setCurrentImage((prevImage) =>
			prevImage < images.length - 1 ? prevImage + 1 : 0
		);
	};
 
	// Handle left arrow key press
	useKeyDown("ArrowLeft", handleLeftArrow);
 
	// Handle right arrow key press
	useKeyDown("ArrowRight", handleRightArrow);
 
	return (
		<div>
			<img src={images[currentImage]} alt={`Image ${currentImage + 1}`} />
		</div>
	);
};

In this example, when the user presses the left arrow key, the handleLeftArrow function is called to navigate to the previous image. Similarly, when the right arrow key is pressed, the handleRightArrow function is called to navigate to the next image.

Conclusion

These are just a few examples of how you can use the useKeyDown hook to enhance the user experience in your React applications. The possibilities are endless, and you can tailor the behavior of the hook to suit your specific use case. Have fun experimenting with keyboard interactions and happy coding! 🚀🎉