Author avatar

Desmond Nyamador

Implement Keyboard Events in React

Desmond Nyamador

  • Oct 19, 2020
  • 3 Min read
  • 121 Views
  • Oct 19, 2020
  • 3 Min read
  • 121 Views
Web Development
Front End Web Development
Client-side Frameworks
React

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.

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

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.

1
2
# Key: Alt has been pressed
# Key: ArrowDown has been pressed
bash

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:

1
2
3
<button onclick="launchApp()">
		Click Me
</button>
jsx

In React this would be done as shown below:

1
2
3
<button onClick={launchApp}>
		Click Me
</button>
jsx

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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>
)
}
jsx

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

1