Guess the Number with React Hooks

Controller input, generating a random number, counting the number of guesses, and more

Cristian Salcescu
Frontend Essentials

--

Photo by Alex Sanislav on Unsplash

In this post, we will create the small game of guessing a number using React.

Let’s start by imagining what the interface for such a game may look like. We can simply display a text input where the user can write the number and a button to check if that number is right.

Ok, let’s do that.

function Game() {
return (
<form>
<input type="number" />
<button type="button">Guess</button>
</form>
);
}
export default Game;

Controlled Input

React does not promote the direct access of an input in order to read its data. To have the latest value of an input we need to associate that input with a state variable. Such an input with both the value and the onChange properties defined is called a controlled input.

First, we defined the associated state.

const [guess, setGuess] = useState("");

And then we associate this state variable with the controlled input.

<input
type="number"
value={guess}
onChange={(e) => setGuess(e.target.value)}
/>

--

--