Listing 11-1: A Number Guessing Game with useState
What number (between 1 and 10) am I thinking of?Your score: 0
import {useState} from 'react';
function NumberGuessing(props){
const [score,setScore] = useState(0);
const [guess,setGuess] = useState('');
const checkNumber =()=>{
const randomNumber = Math.floor(Math.random() * 10)+1;
if (Number(guess) === randomNumber){
setScore(()=>score+1);
}
}
return (
<>
What number (between 1 and 10) am I thinking of?
<input value={guess}
type="number"
min="1"
max="10"
onChange={(e)=>setGuess(e.target.value)}
/>
<button onClick={checkNumber}>Guess!</button>
<p>Your score: {score}</p>
</>
)
}
export default NumberGuessing;
Download the examples, report issues, and ask/answer questions in the discussion area by visiting the book's github page. All of the code for the book is also available on codesandbox.io for you to play around with.
ReactJS Foundations is published by John Wiley and Sons, Inc and is available in paperback and eBook.