From 552f0f0216d8ab2329acf3d1206f9918f019b1dc Mon Sep 17 00:00:00 2001 From: Denys Khuda Date: Fri, 9 Aug 2024 18:10:37 +0300 Subject: [PATCH] add component with pressedKey --- src/App.tsx | 40 +++++++++++++++++++++++++++++++++++----- 1 file changed, 35 insertions(+), 5 deletions(-) diff --git a/src/App.tsx b/src/App.tsx index f819cbdb9..1b3379d79 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -1,7 +1,37 @@ import React from 'react'; -export const App: React.FC = () => ( -
-

The last pressed key is [Enter]

-
-); +type State = { + lastPressedKey: string; +}; + +export class App extends React.Component<{}, State> { + state: State = { + lastPressedKey: '', + }; + + handleKeyBoard = (event: KeyboardEvent) => { + this.setState({ + lastPressedKey: event.key, + }); + }; + + componentDidMount(): void { + document.addEventListener('keyup', this.handleKeyBoard); + } + + componentWillUnmount(): void { + document.removeEventListener('keyup', this.handleKeyBoard); + } + + render() { + return ( +
+

+ {this.state.lastPressedKey + ? `The last pressed key is [${this.state.lastPressedKey}]` + : 'Nothing was pressed yet'} +

+
+ ); + } +}