How to Use Keyboard Event Handler in React TypeScript

Last updated on: by Digamber

Ideally, events are handled through mouse clicks and by pressing keyboard buttons. In this guide, we will learn how to handle events through Keyboard in React and TypeScript application.

In this article, we will cover how to use KeyboardEvent to manage HTML divs movement through keyboard buttons in React TypeScript.

To make you understand the keyboard event handling concept in React, we will create a small feature. There will be 2 HTML divs that will move inside the screen when pressing the key up, down, left, and right.

To manage the events, we’ll use KeyboardEvent with the HTMLDivElement interface.

KeyboardEvent is an object that allows the user to interact with the keyboard. It offers various event types such as keydown, keypress, or keyup in conjunction with the type of event triggered from the keyboard.

The HTMLDivElement interface provides unique properties (beyond the regular HTMLElement interface; it is also available to it by inheritance) for manipulating

elements.

Install New React App

To install a new React project, you need to execute the following command, and this command will create a React TypeScript application.

After the project is downloaded, move into the project folder.

npx create-react-app react-typescript-demo --template typescript
cd react-typescript-demo

Build Component File

After, getting into the project make the features/ directory, also make the new component file by the name of Profile.tsx file.

import React from 'react'
function Profile() {
  return (
    <div></div>
  )
}
export default Profile

Handle Keyboard Events in React

We have combined the keyboard events with custom function, make sure to add the following code into the features/Profile.tsx file.

import React from "react";
const Profile = () => {
  const [left, setLeft] = React.useState(0);
  const [top, setTop] = React.useState(0);
  const keyDownEvent = (event: React.KeyboardEvent<HTMLDivElement>) => {
    console.log(event.code);
    if (event.code === "ArrowRight") {
      setLeft(() => left + 15);
    }
    if (event.code === "ArrowLeft") {
      setLeft(() => left - 15);
    }
    if (event.code === "ArrowDown") {
      setTop(() => top + 15);
    }
    if (event.code === "ArrowUp") {
      setTop(() => top - 15);
    }
  };
  return (
    <div>
      <h2>React Keyboard Event Handling Example</h2>
      <div className="container" onKeyDown={keyDownEvent} tabIndex={0}>
        <div className="moveable" style={{ top: top, left: left }}></div>
      </div>
    </div>
  );
};
export default Profile;

Incorporate Custom CSS

We need to design the basic layout which contains two blocks, which will move on keyboard button press.

Hence, enter into the src/App.css file and paste the following.

body {
  text-align: center;
}
.container {
  margin: 40px auto;
  width: 700px;
  height: 340px;
  overflow: hidden;
  position: relative;
  background: rgb(86, 5, 247);
}
.moveable {
  width: 50px;
  height: 50px;
  left: 0;
  position: absolute;
  border: 5px solid #efefef;
  background: rgb(254, 211, 22);
}

Add Component in App Js

You have to add the Profile component into the src/App.js file, this way it will be available throughout our React project.

import "./App.css";
import Profile from "./features/Profile";
function App() {
  return (
    <div className="App">
      <Profile />
    </div>
  );
}
export default App;

Start Development Server

In the final step, we require to run the react application. For that you have to execute the following command.

npm start

How to Use Keyboard Event Handler in React TypeScript

Digamber

I am Digamber, a full-stack developer and fitness aficionado. I created this site to bestow my coding experience with newbie programmers. I love to write on JavaScript, ECMAScript, React, Angular, Vue, Laravel.