Using onKeyDown on a certain element will require focus to work as intended.

We can make your MdOutlinePause component focus-able by adding the tabindex attribute. That will allow you to give the icon focus by hitting tab or by clicking on it. The element would look something like this:

<MdOutlinePause tabIndex={0} onKeyDown={handleKey} />

If you want to detect the key event without having to focus the element, you will need to attach an event listener. We can do this with useEffect so this happens onMount, and we'll attach the event listener to the window so it works regardless of which element has focus:

  /// Don't copy and paste this - see below
  useEffect(() => {
    window.addEventListener("keydown", handleKeyPress);
    });
  }, []);
  /// Don't copy and paste this - see below

This allows you to detect the keyboard event, which is great, but there's an issue: the eventListener gets added again whenever the page mounts, but is never removed. So you will likely run into issues of your function getting called multiple times on each keyPress.

We can fix this by removing the event listener in the return from useEffect. This is how we specify a function to let the useEffect clean up after itself. This ensures that our useEffect is never adding more than one "keydown" event listener at a time:

  useEffect(() => {
    window.addEventListener("keydown", handleKeyPress);

    return () => {
      window.removeEventListener("keydown", handleKeyPress);
    };
  }, []);

Here's a full example on codesandbox

This works great if you don't need to access state in your handleKeyPress function.


It is a common use case to need to do something with state variables when the user does a certain action, and if we need to access updated state then we run into a problem: we attached handleKeyPress to the event listener onMount and the function never gets updated, so it will always use the initial version of state. This codesandbox illustrates the issue.

We can fix this by adding handleKeyPress to the dependencies array for useEffect, but this results in our event listener being removed and re-added on every render since handleKeyPress will be updated on each render. A better solution is to use the callback pattern with our handleKeyPress so that it is only updated when actually necessary (when the state it depends on is updated). We also want to add handleKeyPress to our useEffect dependency array so we create a new event listener when the handleKeyPress function changes:

  const handleKeyPress = useCallback((event) => {
    // do stuff with stateVariable and event
  }, [stateVariable]);

  useEffect(() => {
    window.addEventListener("keydown", handleKeyPress);

    return () => {
      window.removeEventListener("keydown", handleKeyPress);
    };
  }, [handleKeyPress]);

Now everything updates appropriately! Here's a full example of this on codesandbox.


There's one more solution which lets you access state in the simplest way possible. The downside is that the only state variable you have access to (with updated values) will be the state variable you are updating, so this solution is situational. To access other state variables, you'll have to use the solution above.

By passing a function to useState, we can access the previous state as the first argument of the function. This allows for a much simpler approach, shown below and in this codesandbox.

  const [text, setText] = useState("");

  const handleKeyPress = event => {
    setText(previousText => `${previousText}${event.key}`);
  };

  useEffect(() => {
    window.addEventListener("keydown", handleKeyPress);

    return () => {
      window.removeEventListener("keydown", handleKeyPress);
    };
  }, []);

Answer from Andrew Hulterstrom on Stack Overflow
Top answer
1 of 1
9

Using onKeyDown on a certain element will require focus to work as intended.

We can make your MdOutlinePause component focus-able by adding the tabindex attribute. That will allow you to give the icon focus by hitting tab or by clicking on it. The element would look something like this:

<MdOutlinePause tabIndex={0} onKeyDown={handleKey} />

If you want to detect the key event without having to focus the element, you will need to attach an event listener. We can do this with useEffect so this happens onMount, and we'll attach the event listener to the window so it works regardless of which element has focus:

  /// Don't copy and paste this - see below
  useEffect(() => {
    window.addEventListener("keydown", handleKeyPress);
    });
  }, []);
  /// Don't copy and paste this - see below

This allows you to detect the keyboard event, which is great, but there's an issue: the eventListener gets added again whenever the page mounts, but is never removed. So you will likely run into issues of your function getting called multiple times on each keyPress.

We can fix this by removing the event listener in the return from useEffect. This is how we specify a function to let the useEffect clean up after itself. This ensures that our useEffect is never adding more than one "keydown" event listener at a time:

  useEffect(() => {
    window.addEventListener("keydown", handleKeyPress);

    return () => {
      window.removeEventListener("keydown", handleKeyPress);
    };
  }, []);

Here's a full example on codesandbox

This works great if you don't need to access state in your handleKeyPress function.


It is a common use case to need to do something with state variables when the user does a certain action, and if we need to access updated state then we run into a problem: we attached handleKeyPress to the event listener onMount and the function never gets updated, so it will always use the initial version of state. This codesandbox illustrates the issue.

We can fix this by adding handleKeyPress to the dependencies array for useEffect, but this results in our event listener being removed and re-added on every render since handleKeyPress will be updated on each render. A better solution is to use the callback pattern with our handleKeyPress so that it is only updated when actually necessary (when the state it depends on is updated). We also want to add handleKeyPress to our useEffect dependency array so we create a new event listener when the handleKeyPress function changes:

  const handleKeyPress = useCallback((event) => {
    // do stuff with stateVariable and event
  }, [stateVariable]);

  useEffect(() => {
    window.addEventListener("keydown", handleKeyPress);

    return () => {
      window.removeEventListener("keydown", handleKeyPress);
    };
  }, [handleKeyPress]);

Now everything updates appropriately! Here's a full example of this on codesandbox.


There's one more solution which lets you access state in the simplest way possible. The downside is that the only state variable you have access to (with updated values) will be the state variable you are updating, so this solution is situational. To access other state variables, you'll have to use the solution above.

By passing a function to useState, we can access the previous state as the first argument of the function. This allows for a much simpler approach, shown below and in this codesandbox.

  const [text, setText] = useState("");

  const handleKeyPress = event => {
    setText(previousText => `${previousText}${event.key}`);
  };

  useEffect(() => {
    window.addEventListener("keydown", handleKeyPress);

    return () => {
      window.removeEventListener("keydown", handleKeyPress);
    };
  }, []);

🌐
GeeksforGeeks
geeksforgeeks.org › reactjs › react-onkeyup-event
React onKeyUp Event - GeeksforGeeks
July 23, 2025 - React onKeyUp is an event listener that is used to detect the key release event in a browser using JavaScript.
Discussions

Firing a button onKeyUp?
I'm fairly certain the onKeyUp event will only work within an input or similar control. You could create the handleKeyUp method as a prop on the button component and then call it from outside of the component if there is an input elsewhere. More on reddit.com
🌐 r/reactjs
4
1
July 27, 2018
I can't catch the JavaScript keyup event of the Input element and call Search method in the HomeController. Net Core 6.
This also works, I go to the HomeController-->Search method, but the page does not react in any way and does not even reload, the transition to the Search.cshtml page does not occur. More on learn.microsoft.com
🌐 learn.microsoft.com
5
0
How to trigger "Tab" keyboard key click from the code
Hi, Is there straight forward way (custom component for example) to trigger “Tab” click or any other keyboard key using code. (I don’t have HTML or JS knowledge) What I am trying to accomplish is to have a button “for example”, when this button clicked; the Tab key click event triggered, ... More on anvil.works
🌐 anvil.works
1
0
July 8, 2020
React & Redux: Adding a Handler for 'Enter Key' Events
I have been working on the React and Redux series of projects. I recently passed the “Manage State Locally” exercise; however, I would like to enhance the functionality of the code I have so far by adding an event handler that will detect an enter key press and trigger the click event on ... More on forum.freecodecamp.org
🌐 forum.freecodecamp.org
1
2
November 20, 2018
🌐
React
react.dev › reference › react-dom › components › common
Common components (e.g. <div>) – React
export default function KeyboardExample() { return ( <label> First name: <input name="firstName" onKeyDown={e => console.log('onKeyDown:', e.key, e.code)} onKeyUp={e => console.log('onKeyUp:', e.key, e.code)} /> </label> ); }
🌐
Felix Gerschau
felixgerschau.com › react-typescript-onkeyup-event-type
TypeScript definition for onKeyUp React event
import React, { KeyboardEvent } from 'react'; const App = () => { const handleKeyboardEvent = (e: KeyboardEvent<HTMLImageElement>) => { // Do something }; return <div onKeyUp={handleKeyboardEvent}>{/** Some code */}</div>; }; export default App; onKeyDown · onKeyDownCapture ·
🌐
W3Schools
w3schools.com › jsref › event_onkeyup.asp
onkeyup Event
The onkeyup event occurs when the user releases a key on the keyboard.
🌐
DevExtreme
js.devexpress.com › React › Documentation › 21_1 › Guide › UI_Components › TextBox › Handle_the_Keyboard_Events
React TextBox - Handle the Keyboard Events | React Documentation v21.1
<template> <DxTextBox @key-down="onKeyDown" @key-press="onKeyPress" @key-up="onKeyUp" @enter-key="onEnterKey" /> </template> <script> import 'devextreme/dist/css/dx.light.css'; import { DxTextBox } from 'devextreme-vue/text-box'; export default { components: { DxTextBox }, methods: { onKeyDown(e) { const keyCode = e.event.key; // Event handling commands go here }, onKeyPress(e) { const keyCode = e.event.key; // Event handling commands go here }, onKeyUp(e) { const keyCode = e.event.key; // Event handling commands go here }, onEnterKey(e) { // Event handling commands go here } } } </script> imp
Find elsewhere
🌐
React
react.dev › reference › react-dom › components › input
<input> – React
When you control an input by passing some value to it, you force it to always have the value you passed. So if you pass a state variable as a value but forget to update that state variable synchronously during the onChange event handler, React ...
🌐
StackBlitz
stackblitz.com › edit › react-input-keyup
React Input Keyup - StackBlitz
Starter project for React apps that exports to the create-react-app CLI.
🌐
Pluralsight
pluralsight.com › tech insights & how-to guides › tech guides & tutorials
How to Use the Enter Key Event Handler on a React-Bootstrap Input Component | Pluralsight
April 16, 2025 - The event onKeyUp checks the event char code being triggered by the end user, and if it is 13, then the event has been generated by the enter key. Otherwise, the state value is not updated into the component state object.
🌐
CodeSandbox
codesandbox.io › s › onkeyup-props-react-select-clcr1
OnKeyUp props react-select - CodeSandbox
December 28, 2019 - Answer question 56240736 stackoverflow
Published   Dec 28, 2019
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › API › Element › keyup_event
Element: keyup event - Web APIs | MDN
Inherits from UIEvent and Event. This interface also inherits properties of its parents, UIEvent and Event. KeyboardEvent.altKey Read only · Returns a boolean value that is true if the Alt (Option or ⌥ on macOS) key was active when the key event was generated.
🌐
Medium
medium.com › @stheodorejohn › exploring-keyboard-and-focus-events-in-react-d6c05d1e4926
Exploring Keyboard and Focus Events in React | by Theodore John.S | Medium
June 28, 2023 - Exploring Keyboard and Focus Events in React Lets unleash the power of interactivity in React with keydown, keyup, keypress, focus, and blur events. Elevate user experiences and create dynamic …
🌐
Reddit
reddit.com › r/reactjs › firing a button onkeyup?
r/reactjs on Reddit: Firing a button onKeyUp?
July 27, 2018 -

Currently have a button that I want to fire using the Enter key in a class component but for some reason it's not working. Any ideas?

  handleKeyUp(event) {
    if (event.keyCode === 13) {
      console.log('Enter key has been pressed')
    }
  }

  render() {
    return(
      <div>
        <button
          onKeyUp={ this.handleKeyUp }
        >
          Submit
        </button>
      </div>
    );
  }
🌐
React
legacy.reactjs.org › docs › events.html
SyntheticEvent – React
onKeyDown onKeyPress onKeyUp · Properties: boolean altKey number charCode boolean ctrlKey boolean getModifierState(key) string key number keyCode string locale number location boolean metaKey boolean repeat boolean shiftKey number which · The key property can take any of the values documented in the DOM Level 3 Events spec. Event names: onFocus onBlur · These focus events work on all elements in the React DOM, not just form elements.
🌐
Roy Tutorials
roytuts.com › home › react js › allow only numeric values or digits in input field using react
Allow only numeric values or digits in input field using React - Roy Tutorials
September 24, 2025 - class NumericInputApp extends React.Component { constructor(props) { super(props); this.allowOnlyNumericsOrDigits = this.allowOnlyNumericsOrDigits.bind(this); } allowOnlyNumericsOrDigits(e) { if(/\D/g.test(e.target.value)) { e.target.value = e.target.value.replace(/\D/g,''); } } render() { return ( <div> <label>Input Here</label>&nbsp;&nbsp;<input onKeyUp={this.allowOnlyNumericsOrDigits.bind(this)}/> </div> ); } } export default NumericInputApp;
🌐
Codetogo
codetogo.io › how-to-listen-to-keyup-event-in-react
How to listen to keyup event in React | Code to go
January 28, 2020 - import React from "react"; function Input() { function handleInputKeyUp(event) { console.log(event.target.value); } return <input onKeyUp={handleInputKeyUp} />; }
🌐
Howtocreate
howtocreate.co.uk › tutorials › javascript › eventinfo
JavaScript tutorial - Event information
//first, tell the browsers to react to the event if( document.captureEvents && Event.KEYUP ) { //remove this part if you do not need Netscape 4 to work document.captureEvents( Event.KEYUP ); } /* this next line tells the browser to detect a keyup event over the whole document and when it detects it, it should run the event handler function 'alertkey' */ document.onkeyup = alertkey; //now create the event handler function to process the event function alertkey(e) { if( !e ) { //if the browser did not pass the event information to the //function, we will have to obtain it from the event register