Recently, I wanted to get keyboard input on the React application.
I thought there is maybe someone like me.
So let's figure out this.
Create a Test Project
$ npx create-react-app react-test --template typescript
Implement
I tried many things to implement this.
Like onKeyDown, onKeyPress in div tag or, addEventListener to window or document in useEffect.
Finally, I found the key point !!
import React, { KeyboardEvent } from "react";
import "./App.css";
function App() {
const detectPressedKey = (ev: KeyboardEvent<HTMLDivElement>) => {
console.log(ev.key, ev.keyCode);
};
return (
<div className="App" onKeyDown={detectPressedKey} tabIndex={0}>
Hello React
</div>
);
}
export default App;
Did you find it?
It was the tabIndex!!
It makes the tag to selectable.
Feel free to try it.
Select the application and press the keys.
It will work well.
'Web > JavaScript' 카테고리의 다른 글
[TypeScript] Utility Types (0) | 2021.03.21 |
---|---|
[Jest] Testing with Error Return (0) | 2020.12.28 |
[TypeScript] Type Inference (0) | 2020.10.25 |
[TypeScript] Decorators (0) | 2020.10.24 |
[TypeScript] Iterators and Generators (0) | 2020.10.23 |
댓글