Sometimes, we need to do something when a key is pressed in our React app.
In this article, we’ll look at how to do something when a key is pressed in our React app.
Handle the KeyPress Event in React
We can handle the keypress event when a key is pressed in React by setting the onKeyPress
prop to an event handler function.
For instance, we can write:
import React from "react";
export default function App() {
const handleKeyPress = (event) => {
if (event.key === "Enter") {
console.log("enter press here! ");
}
};
return (
<>
<input type="text" onKeyPress={handleKeyPress} />
</>
);
}
We have the handleKeyPress
function that takes the event
object as a parameter.
The event
object has the key
property which is set to the string with the key name that’s pressed.
Therefore, we can use it to check if the enter key is pressed by checking aginst the event.key
property.
When enter is pressed in the input, the console log will run.
Conclusion
We can handle the keypress event when a key is pressed in React by setting the onKeyPress
prop to an event handler function.