Categories
JavaScript Answers

How to detect Shift + Enter press in React onKeyPress event?

Spread the love

Sometimes, we want to detect Shift + Enter press in React onKeyPress event.

In this article, we’ll look at how to detect Shift + Enter press in React onKeyPress event.

How to detect Shift + Enter press in React onKeyPress event?

To detect Shift + Enter press in React onKeyPress event, we can check if shift+enter is pressed from the keypress event object.

For instance, we write:

import React from "react";

export default function App() {
  const handleKeyPress = (e) => {
    if (e.key === "Enter" && e.shiftKey) {
      console.log("pressed shift+enter");
    }
  };

  return (
    <div>
      <input onKeyPress={handleKeyPress} />
    </div>
  );
}

to set the onKeyPress prop of the input to the handleKeyPress function.

We check if e.key is 'Enter' and e.shiftKey is true to check if shift+enter is pressed.

Therefore, if we press both keys together, we see "pressed shift+enter" logged.

Conclusion

To detect Shift + Enter press in React onKeyPress event, we can check if shift+enter is pressed from the keypress event object.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *