Import the Card Component

Import hooks and components

We’ll import Card.js and pass the data to the Card component in the App.js file so that we can view the real layout of the cards. Before doing that, however, let’s first import hooks like useState and useEffect. Then we’ll create some states to select the cards, as well as the disabled state.

In the following snippet, choiceOnce and choiceTwo hold the state of the card that’s being flipped by us in the turn, and setChoiceOne and setChoiceTwo are the functions that update the state. The disabled variable holds the state of the flipped card. If it’s true, the card doesn’t flip back, and if it’s false, the card does flip back.

import { useEffect, useState } from "react";
import Card from "./Card/Card";

// It will handle the state of the selection of the first card 
const [choiceOne, setChoiceOne] = useState(null);

// It will handle the state of the selection of the second card 
const [choiceTwo, setChoiceTwo] = useState(null)

// It will handle if the card is disabled 
const [disabled, setDisabled] = useState(false);

Define the handleChoice function

If disabled isn’t true, the handleChoice function in the Card.js file is called, with the selected card as the argument. If our choiceOne state isn’t null, the selected card passes to setChoiceTwo. Otherwise, it passes to setChoiceOne. Let’s define the handleChoice function in the following snippet:

const handleChoice = (card) => {
   choiceOne ? setChoiceTwo(card) : setChoiceOne(card);
};

Define the reset function

After we’ve made a guess, correct or otherwise, we have to reset all state values and increase the value of turns by one. The following snippet shows how we define the reset function:

function reset() {
  setChoiceOne(null);
  setChoiceTwo(null);
  setDisabled(false);
  setTurns((prevTurns) => prevTurns + 1);
}

Check the selected cards

On each render, we use the useEffect hook to check whether card one and card two are the same. We leave them flipped if they’re the same. Otherwise, we flip them back. We use the src property to see if the selected cards have the same image. If they’re the same, we modify the matched property to true, allowing us to use our flipped class on these cards.

In addition, if the src property is the same for both cards, we map over all previous cards and set the matched property of the same selected card to true. If the selected cards don’t have the same src property, we call the reset function after 500 milliseconds, which flips the cards back and resets the state values to the initial values. Here, we pass the choiceOne and choiceTwo as the dependencies so that useEffect calls the function whenever the dependencies change.

The following snippet provides an overview of this:

Get hands-on with 1400+ tech skills courses.