0
0
ReactDebug / FixBeginner · 3 min read

How to Handle onKeyPress Event in React: Fix and Best Practices

In React, handle the onKeyPress event by passing a function to the onKeyPress prop of an input or element. Use the event object inside the handler to check which key was pressed and respond accordingly.
🔍

Why This Happens

Developers often try to use onKeyPress incorrectly by either not passing a function or by using deprecated event properties. Also, React's onKeyPress only works on certain elements like inputs and textareas, so attaching it to unsupported elements causes no response.

jsx
function MyComponent() {
  return (
    <input onKeyPress={handleKeyPress} />
  );
}

function handleKeyPress(event) {
  if (event.key === 'Enter') {
    alert('Enter pressed');
  }
}
Output
Warning: Expected a function for onKeyPress but got a string. No alert on Enter key press.
🔧

The Fix

Pass a function directly to onKeyPress as a prop, not a string. Use the event's key property to detect which key was pressed. This works on input elements and triggers your handler correctly.

jsx
import React from 'react';

function MyComponent() {
  const handleKeyPress = (event) => {
    if (event.key === 'Enter') {
      alert('Enter pressed');
    }
  };

  return (
    <input onKeyPress={handleKeyPress} placeholder="Press Enter" />
  );
}

export default MyComponent;
Output
When you press Enter inside the input box, an alert pops up saying 'Enter pressed'.
🛡️

Prevention

Always pass a function to event handlers in React, never a string. Use event.key instead of deprecated properties like event.keyCode. Test your handlers on supported elements like inputs or textareas. Use linting tools like ESLint with React plugin to catch common mistakes early.

⚠️

Related Errors

Common related errors include using onkeypress (all lowercase) instead of onKeyPress, which React does not recognize, or trying to use onKeyPress on non-interactive elements like div without tabIndex, which prevents the event from firing.

Key Takeaways

Always pass a function, not a string, to the onKeyPress prop in React.
Use event.key to detect which key was pressed inside the handler.
Attach onKeyPress only to elements that support keyboard input like input or textarea.
Use ESLint with React rules to catch event handler mistakes early.
Avoid deprecated event properties like event.keyCode; prefer event.key.