Practice project to stay sharp: React Typing Game (Part 2)

Alex Foreman
3 min readFeb 1, 2021

--

In my last blog I covered the basics of setting up a typing game using React. My primary concerns then were to demonstrate the processes of fetching a random word from the Wordnik API and triggering a new word if the user input matched. I also had a dropdown menu allowing the user to select three levels of difficulty, which changed the minimum and maximum number of letters of called words. To implement these features, I used a less than ideal state management and component structure.

This week, I will demonstrate my refactor to improve the app’s architecture and better suit React’s modular component structure. I will also show how I enhanced the game’s complexity and began styling with styled components.

According to the React docs, a component should really only do one thing. I can’t say that I removed the complexity of all components to a singular purpose, but I did separate the visual elements from the logic.

In its current state, the app is laid out and behaves as follows.

Countdown tells the timer and word display components to show us what’s up.

The Countdown component behaves as it sounds, making use of setInterval and useEffect to subtract one second from the original state (beginning at 10 seconds). The seconds state is passed to the Timer component, which then displays the countdown or “Game Over” at zero seconds. The Countdown component also determines whether the WordReceiver component displays the API word, or whether it disappears, as it does when time runs out.

The WordReceiver component displays the random word from Wordnik.

During this iteration of the game, the timer begins on page load.

A Start component triggers the first API call with a button click. All subsequent calls are dynamically generated based on user input.

The Typer component above is responsible for handling the user’s input and calling the next word from the API. The length of generated words — and difficulty — increases as the game progresses.

Getting closer.

This is still not a finished product, but I have begun to enhance the styling, primarily with the countdown clock. I used styled components to wrap the Timer component. The variation in color is achieved by setting the background to radial-gradient. You can specify the colors used in the gradient, which can also be set to percentages.

With these improvements, the React typing game has a much more polished look and is ready for a short game.

--

--