I. Overview
In this article I will being going over how to create a simple multiple choice game using React. In this walkthrough we will be creating a 'color guessing game' that can be used to familiarize yourself with the hex values of different colors. Building apps like these are a great way to solidify your understanding on the usage of React hooks as they are foundational in what makes the React framework so powerful!
Take a look at the final product on CodeSandbox here.
II. Setup
Here is the basic HTML that we will use for our app. We will add in the rest later.
<div style={{ display: 'flex', flexDirection: 'column' }}>
<h1 style={{ textAlign: 'center' }}>Pick the Color Value</h1>
<div className={styles.container}>
<div style={{ backgroundColor: `${divColor}` }} className={styles.colorBox}>
<span>{INCORRECT/CORRECT DISPLAY GOES HERE}</span>
</div>
</div>
<div className={styles.buttonContainer}>
{WHERE MULTIPLE CHOICE OPTIONS GO HERE}
</div>
<p style={{ textAlign: 'center' }}>{CORRECT ANSWER COUNT GOES HERE}</p>
<p style={{ textAlign: 'center' }}>{INCORRECT ANSWER COUNT GOES HERE}</p>
</div>
III. Generating values for initial render of our app
Lets start by initializing the random color that will be displayed in our container box. We will do this by using the 'useState'
hook, and giving it an initial value.
- Create a function that return 3 random hex values in an array
getRandomHexArray()
.
const getRandomHexArray = () => {
const value1 = ('#' + Math.floor(Math.random() * 16777215).toString(16))
const value2 = ('#' + Math.floor(Math.random() * 16777215).toString(16))
const value3 = ('#' + Math.floor(Math.random() * 16777215).toString(16))
return [value1, value2, value3]
}
- Now we want to create a variable
initialRandomArray
that will call the function we just created on each render, so we will have a new random array of hex values every time there is a state change.
let initialRandomArray = getRandomHexArray();
- We also need a state that holds a random value of range 0-initialRandomArray.length. This will decide which color code is "Correct" for each question. And we will create another state to hold our
initialRandomArray
as well.
const [answerIndex, setAnswerIndex] = useState(Math.floor(Math.random()*3))
const [hexArray, setHexArray] = useState(initialRandomArray);
IV. Displaying buttons using map()
<div className={styles.buttonContainer}>
{WHERE MULTIPLE CHOICE OPTIONS GO HERE}
</div>
Now we will finish this code to properly display our multiple choice options that the user will be clicking on.
<div className={styles.buttonContainer}>
{hexArray.map((button, index) => {
return (
<button key={index} className={styles.button} onClick={()=>{handleSubmit(index)}}>{hexArray[index].toUpperCase()}</button>
)
})}
This code returns a element for every value we have inside hexArray
. We pass a child to the element of {hexArray[index].toUpperCase()}
which displays the hex code on each of our buttons. We also pass to our onClick property a arrow function that runs our submission handler function which we will create now.
V. Handling submissions
const handleSubmit = (index: any) =>{
hexArray[index] == hexArray[answerIndex] ? handleCorrect() : handleIncorrect()
let newRandomArray = getRandomHexArray()
setHexArray(newRandomArray)
setAnswerIndex(Math.floor(Math.random() * 3))
setIsOpen(true)
setTimeout(()=> setIsOpen(false), 1000)
}
const handleCorrect = () =>{
setIsCorrect(true)
}
const handleIncorrect = () =>{
setIsCorrect(false)
}
This function does a few things:
- It checks to see if the answer was correct by passing on index of the click event and comparing that to the hexArray at the answerIndex variable we store.
- Generates a new random array
newRandomArray
- Sets isOpen to true, which lets us conditionally render feedback for the user to display 'Correct' or 'Incorrect' on each question as shown below.
<div style={{ backgroundColor: `${hexArray[answerIndex]}` }} className={styles.colorBox}>
<span className={styles.colorBoxText}> {isOpen ? isCorrect ? 'Correct!' : 'Incorrect' : ''}</span>
</div>
- The setTimeout allows us to only display the 'Correct/Incorrect' text briefly for 1000 milliseconds by running an arrow function to set our
isOpen
variable back tofalse
.
There you go! Your first React game using hooks.
Extra Credit: Add a count for incorrect and correct answers using useRef
Author: Evan Ryan
OrangeSpark Solutions
Top comments (0)