From 008bdebd5bbfbe55e59fc7a4afb5be4e810e0a9e Mon Sep 17 00:00:00 2001 From: Anatolii Lykhohodenko Date: Thu, 20 Jul 2023 17:50:19 +0300 Subject: [PATCH] solution --- src/App.tsx | 60 ++++++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 55 insertions(+), 5 deletions(-) diff --git a/src/App.tsx b/src/App.tsx index f819cbdb9..14769a419 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -1,7 +1,57 @@ import React from 'react'; -export const App: React.FC = () => ( -
-

The last pressed key is [Enter]

-
-); +// class component + +export class App extends React.Component { + state = { + pressedKey: 'Nothing was pressed yet', + }; + + componentDidMount(): void { + document.addEventListener('keyup', this.handleKeyUp); + } + + componentWillUnmount(): void { + document.removeEventListener('keyup', this.handleKeyUp); + } + + handleKeyUp = (event: KeyboardEvent) => { + this.setState(({ pressedKey: `The last pressed key is [${event.key}]` })); + }; + + render() { + return ( +
+

{this.state.pressedKey}

+
+ ); + } +} + +// functional component + +// export const App: React.FC = () => { +// const [char, setChar] = React.useState(''); +// const isFirstRender = React.useRef(true); + +// if (char) { +// isFirstRender.current = false; +// } + +// const handleKeyUp = (event: KeyboardEvent) => setChar(event.key); + +// document.addEventListener('keyup', handleKeyUp); + +// return ( +//
+// {!isFirstRender.current +// ? ( +//

+// {`The last pressed key is [${char}]`} +//

+// ) : ( +//

Nothing was pressed yet

+// )} +//
+// ); +// };