Explorer
project
App.js
index.html
index.js
styles.css
Dependencies
react-dom@16.10.2
react@16.10.2
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
import React, {useState, useEffect, useRef} from "react"
/**
* Challenge:
*
* Move the "business logic" into a custom hook, which will provide
* any parts of state and any functions to this component to use.
*
* You can easily tell which parts the component needs by looking at
* the variables being used inside the `return`ed markup below.
*/
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)
const textBoxRef = useRef(null)
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("")
textBoxRef.current.disabled = false
textBoxRef.current.focus()
}
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
ref={textBoxRef}
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