React is an easy to use JavaScript framework that lets us create front end apps.
In this article, we’ll look at how to create a coin flip app with React and JavaScript.
Create the Project
We can create the React project with Create React App.
To install it, we run:
npx create-react-app coin-flip
with NPM to create our React project.
Create the Coin Flip App
To create the coin flip app, we write:
import React, { useMemo, useState } from "react";
const faces = ["heads", "tails"];
export default function App() {
const [selectedFace, setSelectedFace] = useState("");
const [coinFlipResult, setCoinFlipResult] = useState("");
const flip = () => {
let index;
if (Math.random() < 0.5) {
index = 0;
} else {
index = 1;
}
setCoinFlipResult(faces[index]);
};
const computerSelectedFace = useMemo(() => {
const face = faces.find((f) => f !== selectedFace);
return face;
}, [selectedFace]);
const isWin = useMemo(() => {
return coinFlipResult === selectedFace;
}, [coinFlipResult, selectedFace]);
const showResult = () => {
if (isWin) {
return <p>you win</p>;
}
return <p>you lost</p>;
};
return (
<div>
<div>
<h1>select a face</h1>
<button onClick={() => setSelectedFace("heads")}>heads</button>
<button onClick={() => setSelectedFace("tails")}>tails</button>
</div>
<p>you selected: {selectedFace}</p>
<p>computer selected: {computerSelectedFace}</p>
<button onClick={flip}>flip coin</button>
{showResult()}
</div>
);
}
We first create the faces
array which has the 'heads'
and 'tails'
values that we can pick from.
Then we define the selectedFace
and coinFlipResult
states to set the selected coin face and the coin flip result respectively.
Next, we have the flip
function to call setCoinFlipResult
to set the coin flip result.
We do that by picking a value from the faces
array randomly.
Next, we define the computerSelectedFace
with the useMemo
hook.
The callback just picks the face that hasn’t been picked by the player.
We watch the selectedFace
value to see which one to pick.
The isWin
variable checks if coinFlipResult
is the same as selectedFace
to determine if the player wins.
Then we have the showResult
to return the result to show to the player.
Below that, we have buttons to let the player pick heads or tails when we click them.
Then we show what the player and the computer selected.
And below that, we have the flip coin button to pick the coin face.
And below that, we call showResult
to show the result.
Conclusion
We can create a coin flip game easily with React and JavaScript.