Skip to content
This repository has been archived by the owner on Jul 14, 2023. It is now read-only.

feat(keyboard-input): Accept keyboard input to let the user type words #2

Open
wants to merge 1 commit into
base: 02-21-init_wordle_Run_create_react_app
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 25 additions & 17 deletions wordle-tutorial/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,24 +1,32 @@
import React from 'react';
import logo from './logo.svg';
import { useEffect, useState } from 'react';
import './App.css';

const LETTERS = "abcdefghijklmnopqrstuvwxyz";

function App() {
// The current word
const [buffer, setBuffer] = useState("");

useEffect(() => {
// Called every time the user presses a key on the page
const handler = (ev: KeyboardEvent) => {
if (ev.key === "Backspace" && buffer.length > 0) {
setBuffer(buffer.slice(0, -1));
} else if (LETTERS.includes(ev.key) && buffer.length < 5) {
setBuffer(buffer + ev.key);
}
};

// Register the handler defined above (and unregister it if we update it and need to re-register a new version)
document.addEventListener("keydown", handler);
return () => {
document.removeEventListener("keydown", handler)
};
}, [buffer]);

return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.tsx</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
<div>
<div>{buffer}</div>
</div>
);
}
Expand Down