scrimba
React Bootcamp Course
Speed Typing Game Part 7
Go Pro!Bootcamp

Bootcamp

Study group

Collaborate with peers in your dedicated #study-group channel.

Code reviews

Submit projects for review using the /review command in your #code-reviews channel

Speed Typing Game Part 7
AboutCommentsNotes
Speed Typing Game Part 7
Expand for more info
App.js
run
preview
console
import React, {useState, useEffect} from "react"

/**
* Challenge:
*
* Make the input box focus (DOM elements have a method called .focus())
* immediately when the game starts
*/

function App() {
const STARTING_TIME = 5

const [text, setText] = useState("")
const [timeRemaining, setTimeRemaining] = useState(STARTING_TIME)
const [isTimeRunning, setIsTimeRunning] = useState(false)
const [wordCount, setWordCount] = useState(0)

function handleChange(e) {
const {value} = e.target
setText(value)
}

function calculateWordCount(text) {
const wordsArr = text.trim().split(" ")
return wordsArr.filter(word => word !== "").length
}

function startGame() {
setIsTimeRunning(true)
setTimeRemaining(STARTING_TIME)
setText("")
}

function endGame() {
setIsTimeRunning(false)
setWordCount(calculateWordCount(text))
}

useEffect(() => {
if(isTimeRunning && timeRemaining > 0) {
setTimeout(() => {
setTimeRemaining(time => time - 1)
}, 1000)
} else if(timeRemaining === 0) {
endGame()
}
}, [timeRemaining, isTimeRunning])

return (
<div>
<h1>How fast do you type?</h1>
<textarea
onChange={handleChange}
value={text}
disabled={!isTimeRunning}
/>
<h4>Time remaining: {timeRemaining}</h4>
<button
onClick={startGame}
disabled={isTimeRunning}
>
Start
</button>
<h1>Word count: {wordCount}</h1>
</div>
)
}

export default App
Console
/index.html
-5:11