From e1227f139a283aa64cbfbdfea01936ad8f58ab05 Mon Sep 17 00:00:00 2001 From: Marina Avramenko Date: Fri, 9 Aug 2024 22:55:47 +0300 Subject: [PATCH] add task solution --- src/App.tsx | 32 ++++++++++++++++++++++++++------ src/App2.tsx | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 61 insertions(+), 6 deletions(-) create mode 100644 src/App2.tsx diff --git a/src/App.tsx b/src/App.tsx index f819cbdb9..b95c8aa95 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -1,7 +1,27 @@ -import React from 'react'; +import React, { useState, useEffect, useCallback } from 'react'; -export const App: React.FC = () => ( -
-

The last pressed key is [Enter]

-
-); +export const App: React.FC = () => { + const [keyPress, setKeyPress] = useState(null); + + const handleKeyPress = useCallback((event: KeyboardEvent) => { + setKeyPress(event.key); + }, []); + + useEffect(() => { + document.addEventListener('keyup', handleKeyPress); + + return () => { + document.removeEventListener('keyup', handleKeyPress); + }; + }); + + return ( +
+

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

+
+ ); +}; diff --git a/src/App2.tsx b/src/App2.tsx new file mode 100644 index 000000000..85ee308a2 --- /dev/null +++ b/src/App2.tsx @@ -0,0 +1,35 @@ +import React from 'react'; + +interface State { + keyPress: string | null; +} + +export class App2 extends React.Component { + state: Readonly = { + keyPress: null, + }; + + componentDidMount(): void { + document.addEventListener('keyup', this.handleKeyPress); + } + + componentWillUnmount(): void { + document.removeEventListener('keyup', this.handleKeyPress); + } + + handleKeyPress = (event: KeyboardEvent) => { + this.setState({ keyPress: event.key }); + }; + + render() { + return ( +
+

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

+
+ ); + } +}