From b9e564d86fdce762c182c14adcf4728efd638e1b Mon Sep 17 00:00:00 2001 From: Sophia Date: Tue, 6 Aug 2024 13:58:21 +0300 Subject: [PATCH] add task solution --- src/App.tsx | 40 +++++++++++++++++++++++++++++++++++----- src/index.tsx | 1 + 2 files changed, 36 insertions(+), 5 deletions(-) diff --git a/src/App.tsx b/src/App.tsx index f819cbdb9..0e9340eaf 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 = { + lastKeyPressed: string | null; +}; + +export class App extends React.PureComponent<{}, State> { + state: State = { + lastKeyPressed: null, + }; + + handleKeyPressed = (event: KeyboardEvent) => { + this.setState({ lastKeyPressed: event.key }); + }; + + componentDidMount(): void { + window.addEventListener('keydown', this.handleKeyPressed); + } + + componentWillUnmount(): void { + window.removeEventListener('keydown', this.handleKeyPressed); + } + + render(): React.ReactNode { + const { lastKeyPressed } = this.state; + + return ( +
+

+ {lastKeyPressed + ? `The last pressed key is [${lastKeyPressed}]` + : 'Nothing was pressed yet'} +

+
+ ); + } +} diff --git a/src/index.tsx b/src/index.tsx index 7d27337cd..8b7750da1 100644 --- a/src/index.tsx +++ b/src/index.tsx @@ -2,5 +2,6 @@ import { createRoot } from 'react-dom/client'; import { App } from './App'; import './index.scss'; +import React from 'react'; createRoot(document.getElementById('root') as HTMLElement).render();