Skip to content

Commit

Permalink
add task solution
Browse files Browse the repository at this point in the history
  • Loading branch information
ZakZh committed Jul 25, 2024
1 parent 1a3e715 commit 6589c5c
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 7 deletions.
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,17 +9,20 @@ Make the `App` a class component with `pressedKey` in the `state`.
- before any key was pressed show the `Nothing was pressed yet` message;
- when a key is pressed show a `The last pressed key is [key]` message;
- use `componentDidMount` to add `keyup` handler:

```ts
// DON'T import KeyboardEvent from React, because it is a regular event
document.addEventListener('keyup', (event: KeyboardEvent) => {
console.log(event.key);
});
```

- use `removeEventListener` to remove a global handler in `componentWillUnmount`.

## Instructions

- Install Prettier Extention and use this [VSCode settings](https://mate-academy.github.io/fe-program/tools/vscode/settings.json) to enable format on save.
- Implement a solution following the [React task guideline](https://github.com/mate-academy/react_task-guideline#react-tasks-guideline).
- Use the [React TypeScript cheat sheet](https://mate-academy.github.io/fe-program/js/extra/react-typescript).
- Open one more terminal and run tests with `npm test` to ensure your solution is correct.
- Replace `<your_account>` with your Github username in the [DEMO LINK](https://<your_account>.github.io/react_keyboard/) and add it to the PR description.
- Replace `<your_account>` with your Github username in the [DEMO LINK](https://ZakZh.github.io/react_keyboard/) and add it to the PR description.
31 changes: 25 additions & 6 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,26 @@
import React from 'react';
import React, { useState, useEffect } 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 [key, setKey] = useState('');

useEffect(() => {
const handleKeyBoardEvent = (event: KeyboardEvent) => {
event.preventDefault();
setKey(event.key);
};

document.addEventListener('keyup', handleKeyBoardEvent);

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

return (
<div className="App">
<p className="App__message">
{key ? `The last pressed key is [${key}]` : `Nothing was pressed yet`}
</p>
</div>
);
};

0 comments on commit 6589c5c

Please sign in to comment.