Lessons about React, Keyboard Input, Forms, Event Listeners and Debugging

Keyboard Controls

document.body.addEventListener('keydown', handleKey);

Yesterday’s Bug

keyHandler = event => {
event.preventDefault();

// Respond to the input
}

The Problem

A screenshot of my tetris app’s game over screen. There is a form to input a nickname and submit score to the leaderboard.
My leaderboard form. Typing in the nickname field had no effect.
function LeaderboardForm(props) {
const [nickname, setNickname] = useState('');

...

return (
<form>
...
<input value={nickname} onChange={setNickname} />
...
</form>
);
}

export default LeaderboardForm;

The Fix

useEffect(() => {
if (props.playing) {
document.body.addEventListener('keydown', props.keyHandler);
} else {
document.body.removeEventListener('keydown', props.keyHandler);
}
}, [props.playing, props.keyHandler]);

Consider Every Case

Lessons Learned

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store