HOWTO · React
How to Get onKeyDown Event to Work With Divs in React
Learn how to effectively use the onKeyDown event with div elements in React. This guide provides practical examples and explanations to enhance user interactions in your web applications. Discover the power of keyboard events and create dynamic interfaces that engage users.
On this page
To handle keyboard input on a React <div>, make the element focusable, give it an onKeyDown handler, and check the event’s key value. Keyboard input must originate at a focused element; this <div> handler can receive events from the <div> itself or from a focused descendant through bubbling. A <div> is a generic container, so use a button or another semantic control instead when the interaction is an action users can activate.
Understand how React handles onKeyDown
React calls onKeyDown when a key goes down while the event target is focused. It reports keyboard input; it does not validate text as a user types. For text entry, use the input’s change event to read the updated value. event.key identifies the meaning of the key (for example, "Enter" or "a"), while event.code identifies its physical keyboard position. A held key may produce repeated keydown events.
onKeyDown is useful for commands and keyboard interaction. It also sees keys such as Shift, Ctrl, Alt, and Escape. React’s onKeyPress is not needed for this pattern; use onKeyDown and check the key and modifier state you care about.
Make a <div> keyboard-focusable
A plain <div> is not included in sequential keyboard navigation. Add tabIndex={0} to let users reach it with Tab. This only makes it focusable; it does not automatically give the container focus or make its handler receive events. The user must move focus to it, and keyboard events are delivered to the focused element (or a focused descendant, with bubbling through its ancestors).
When the element is meant to perform an action, prefer a native <button>: it already supports keyboard interaction and communicates its role to assistive technology. A focusable <div> is appropriate for a custom widget only when you also implement the expected role, state, and keyboard behavior for that widget.
Handle keys in a React component
This complete browser page uses a React component to keep the focusable <div>, key handler, and visible state message together. In a React project, use the App component with the project’s normal entry point and React dependencies. Tab to the bordered area, then press Enter to render the message inside it. This page is source for a browser example; it is not the runtime example below.
<div id="root"></div>
<script src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<script type="text/babel">
function App() {
const [message, setMessage] = React.useState("Press Enter");
function handleKeyDown(event) {
if (event.key === "Enter") {
setMessage("Enter received");
}
}
return (
<div
tabIndex={0}
onKeyDown={handleKeyDown}
style={{ border: "1px solid", padding: "1rem", width: "16rem" }}
>
{message}
</div>
);
}
ReactDOM.createRoot(document.getElementById("root")).render(<App />);
</script>
Run this JavaScript example:
function handleKeyDown(event) {
if (event.key === "Enter") {
console.log("Enter received");
}
}
handleKeyDown({ key: "Enter" });
Enter received
The JavaScript example isolates the key check and its output; the React component above shows how to attach the handler and render the result. In your React page, focus the <div> with Tab, press Enter, and observe the state-backed message. The browser-page example depends on its React and Babel scripts loading; in an existing React project, use the component without those page-level script tags.
Handle modifier-key combinations
Modifier state is available on the same event. To handle exactly Ctrl+M, require event.ctrlKey, require event.key.toLowerCase() === "m", and reject event.shiftKey, event.altKey, and event.metaKey. The complete condition is event.ctrlKey && !event.shiftKey && !event.altKey && !event.metaKey && event.key.toLowerCase() === "m". This excludes Ctrl+Shift+M, Ctrl+Alt+M, and Ctrl+Meta+M. If extra modifiers should be accepted, omit only the checks for those modifiers and describe that choice clearly. Use event.metaKey for Command on macOS, or accept either event.ctrlKey || event.metaKey when the shortcut should work on both platforms; in that case, still decide explicitly whether Shift and Alt are allowed.
Browsers and operating systems reserve some shortcuts, and a web page cannot reliably override every system command. If your application owns a key combination that also has a browser default, call event.preventDefault() only for that matched combination and only when suppressing the default is appropriate. Avoid intercepting ordinary typing in inputs or text areas.
Test and troubleshoot keyboard handling
If the handler does not respond, first click the target or use Tab until it has focus, then press the key again. Confirm that tabIndex={0} is present on a generic <div> and that onKeyDown is attached to the element that receives focus or one of its ancestors. Check spelling and capitalization: event.key may be "Enter", "Escape", or a lowercase letter, so compare against the value you intend to handle. For modifier shortcuts, inspect the relevant ctrlKey, altKey, shiftKey, or metaKey property too.
Finally, make sure the result is observable. A state update should render the changed value, while console.log appears in the browser’s developer console. If you need text typed into a field, place the handler on the focused input or use its change event instead. A keyboard handler alone does not make a generic <div> an accessible interactive control.