Skip to content

Commit

Permalink
add task solution
Browse files Browse the repository at this point in the history
  • Loading branch information
AvramenkoMarina committed Aug 9, 2024
1 parent 1a3e715 commit e1227f1
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 6 deletions.
32 changes: 26 additions & 6 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,27 @@
import React from 'react';
import React, { useState, useEffect, useCallback } from 'react';

export const App: React.FC = () => (
<div className="App">
<p className="App__message">The last pressed key is [Enter]</p>
</div>
);
export const App: React.FC = () => {
const [keyPress, setKeyPress] = useState<string | null>(null);

const handleKeyPress = useCallback((event: KeyboardEvent) => {
setKeyPress(event.key);
}, []);

useEffect(() => {
document.addEventListener('keyup', handleKeyPress);

return () => {
document.removeEventListener('keyup', handleKeyPress);
};
});

return (
<div className="App">
<p className="App__message">
{keyPress
? `The last pressed key is [${keyPress}]`
: 'Nothing was pressed yet'}
</p>
</div>
);
};
35 changes: 35 additions & 0 deletions src/App2.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import React from 'react';

interface State {
keyPress: string | null;
}

export class App2 extends React.Component<State> {
state: Readonly<State> = {
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 (
<div className="App">
<p className="App__message">
{this.state.keyPress
? `The last pressed key is [${this.state.keyPress}]`
: 'Nothing was pressed yet'}
</p>
</div>
);
}
}

0 comments on commit e1227f1

Please sign in to comment.