React Js TypeScript Keyboard Event Handler Tutorial

Event handler plays essential roles in handling events. In general, events are triggered through the mouse. However, sometimes user needs to fire events through keyboard buttons.

This post will show you how to handle keyboard events in React TypeScript app using the KeyboardEvent object.

KeyboardEvent objects allow user interaction through the keyboard. Whenever a key is pressed from the keyboard, It invokes an event.

We will create a React TypeScript app to handle keyboard events in React. Then, create two divs — A small div inside a large div will move up, down, right, and left. We’ll use KeyboardEvent with the HTMLDivElement interface to fire events from the keyboard.

The HTMLDivElement interface offers special properties (beyond the standard HTMLElement interface, it also has available to it by inheritance) for manipulating div elements.

Create React Project

Let us start with building a fresh new React TypeScript app; Run the following command.

npx create-react-app react-ts-app --template typescript

Head over to project directory.

cd react-ts-app

Create New Component

Land into the the src/ directory, make components/ folder then create Home.tsx file.

import React from 'react'

function Home() {
  return (
    <div>Home</div>
  )
}

export default Home

Manage Keyboard Events

Now, we are all set to implement the code into the components/Home.tsx file.

import React from "react";

const Home = () => {
  const [moveLeft, setMoveLeft] = React.useState(0);
  const [moveTop, setMoveTop] = React.useState(0);

  const keyDownEvent = (e: React.KeyboardEvent<HTMLDivElement>) => {
    console.log(e.code);

    if (e.code === "ArrowRight") {
      setMoveLeft(() => moveLeft + 10);
    }

    if (e.code === "ArrowLeft") {
      setMoveLeft(() => moveLeft - 10);
    }

    if (e.code === "ArrowDown") {
      setMoveTop(() => moveTop + 10);
    }

    if (e.code === "ArrowUp") {
      setMoveTop(() => moveTop - 10);
    }
  };

  return (
    <>
      <h2>React Keyboard Event Handling Example</h2>
      <div className="wrapper" onKeyDown={keyDownEvent} tabIndex={0}>
        <div className="block" style={{ top: moveTop, left: moveLeft }}></div>
      </div>
    </>
  );
};

export default Home;

Style Component with CSS

We have to write the custom CSS code to design the two div elements; therefore get into the src/App.css file then put the code into file.

body {
  text-align: center;
}

.wrapper {
  margin: 50px auto;
  width: 600px;
  height: 350px;
  position: relative;
  overflow: hidden;
  background: rgb(126, 5, 247);
}

.block {
  width: 80px;
  height: 80px;
  position: absolute;
  left: 0;
  background: rgb(254, 146, 22);
  border: 4px solid #fff;
}

Update Global Component

You have to register the Home component in the global component, hence move to the src/App.js file, and insert the code into the file.

import React from "react";
import "./App.css";
import Home from "./components/Home";

function App() {
  return (
    <div className="App">
      <Home />
    </div>
  );
}

export default App;

Run React Server

You have to run the React app, thus invoke the suggested command from the terminal.

npm start

If you are developing this feature locally, run the app with the URL.

http://localhost:3000

React Js TypeScript Keyboard Event Handler Tutorial

Conclusion

This tutorial taught us how to arrange all the methods and properties to handle Keyboard Events in React.