Skip to content

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

Implement Keyboard Events in React

You can listen for keydown and keyup events, which indicate when a user presses or releases keyboard keys.

Oct 19, 2020 • 3 Minute Read

Introduction

Events such as a click of a mouse button, scrolling, a key press, or a drag of a component—to mention but a few—help developers capture specific actions from users and show feedback or take action based on the action of the user. In this guide, you'll focus solely on keyboard events and how to handle them in React.

Events In JavaScript

In JavaScript, events are simply an indication that a user has performed a particular action. You can listen for keydown and keyup events, which indicates when a keyboard key is pressed or released.

Here's a typical example block of code for implementing keyboard events with JavaScript. The following codeblock logs a statement that shows the particular key pressed by the user.

      document.addEventListener('keydown', function(event){
		console.log(`Key: ${event.key} with keycode ${event.keyCode} has been pressed`);
)
    

Notice that each key has a unique identifier available in the KeyboardEvent passed to the callback function. The codeblock above shows the following in the console when a key is pressed.

      # Key: Alt has been pressed
# Key: ArrowDown has been pressed
    

Events In React

Handling events in React are a bit different from events in HTML. For example, a click handler in HTML will be done as follows:

      <button onclick="launchApp()">
		Click Me
</button>
    

In React this would be done as shown below:

      <button onClick={launchApp}>
		Click Me
</button>
    

What are the key differences here? 🤔

  1. Events in React are named in camelCase .
  2. Rather than passing a string representation of the function, in React you pass the function itself as the handler inside curly braces due to JSX.

Keyboard Events In React

With your generic knowledge of events in React so far, you can now implement keyboard events in React. As mentioned earlier, there are two keyboard events that can be used, the keyup and keydown events.

Now you'll build a simple quiz app that marks a user based on a yes or no answer.

First, set up create-react-app or visit https://react.new to get a fully configured React environment via codesandbox.

      import React from 'react';

function Quiz(){
	handleAnswerChange(event){
		if(event.key === 'y'){
			alert('The sky is your starting point!')
	}
		else if (event.key === 'n') {
			alert('The sky is your limit👀')
	}
}

	return (
		<div>
				<p> Are You Smart?</p>
					<input type="text" value={answer} onKeyPress={handleAnswerChange}/>
				<small> Press Y for Yes or N for No</small>
	</div>
)
}
    

The code block above implements a simple function called handleAnswerChange, which checks whether the key pressed is y for yes or n for no. The value y or n is obtained from the keypress event listener on the input element.

Conclusion

Whew! That's it for this guide. You've compared and contrasted events in React and HTML and gained understanding of how to implement keyboard events in React. To learn more, read the official documentation on keyboard events and handling events in React.

Feel free to get in touch on Twitter as well: @DesmondNyamador