@ryvora/react-use-escape-keydown
v2.0.0
Published
⌨️💨 Listen for Escape keydown in React. Instantly dismiss modals, popovers, and more!
Maintainers
Readme
use-escape-keydown ⌨️💨
Greetings, Escape Route Planner! 🗺️
The use-escape-keydown hook is a simple yet effective utility that listens for the "Escape" key being pressed and calls a provided callback function when it happens.
It's your quick exit strategy 🚪 for modals, popovers, dropdowns, or any UI element that should be dismissible with the Esc key!
Why it's handy:
- Accessibility: Pressing Escape to close transient UI elements is a common and expected keyboard interaction pattern.
- Simplicity: Abstracts away the
useEffectand event listener setup for this specific common case.
Basic Usage:
import { useEscapeKeydown } from '@ryvora/react-use-escape-keydown'; // Hook name might vary
import React, { useState } from 'react';
function MyModal({ isOpen, onClose }) {
useEscapeKeydown(onClose, { disabled: !isOpen }); // Only listen if modal is open
if (!isOpen) return null;
return (
<div className="modal-overlay">
<div className="modal-content">
<p>Press ESC to close me!</p>
<button onClick={onClose}>Close Manually</button>
</div>
</div>
);
}
function App() {
const [modalOpen, setModalOpen] = useState(false);
return (
<>
<button onClick={() => setModalOpen(true)}>Open Modal</button>
<MyModal isOpen={modalOpen} onClose={() => setModalOpen(false)} />
</>
);
}Provide your users with a swift and familiar way to say "Nope, I'm outta here!" 👋💨
