ML
McKayla Lankau
Jan 21, 2022

Tarot Card Reading function in React 🔮

Recently, I’ve been working on a React application that is proving to be just the fruitful learning experience I’d hoped for. My partner and I are building a Tarot Card Reading app (fun! 🔮). Although there is a plethora of different card spreads one can perform in the world of tarot card reading, we decided to start with just a simple 3-card past/present/future spread like so:

In order to achieve this, we needed to write a function that could select 3 different cards from our database(AKA deck of tarot cards) at random(AKA through clairvoyance) without choosing the same card twice. So how did we do it?

First of all, we created a database with Ruby on Rails to hold all of our card data. I will not go into that here, but just know that the “/card” route contains all the cards.

In our React Component, we first call a fetch method to get all of the cards from the database and store them in the state using the { useState } hook.

Great, so this means that we can refer to the card variable anywhere else in this component to get the array of all our cards. That is what we do in the getThreeCards function below. We also created a threecards variable using the { useState } hook again, so that we can fill it with our three randomly selected cards later.

To break down what we are doing here, we are:

  1. setting threeCards to an empty array
  2. creating a loop to run until the threeCards array has 3 cards in it
  3. choosing a newCard from the previously declared card array, with an index of a random number between 1 and 78(the number of cards in a tarot deck)
  4. pushing the newCard to the threeCards array if it was not already chosen. indexOf() is an array method that returns the index of threeCards at which newCard can be found. If it doesn’t find it at all, it returns -1. That’s just how indexOf() works. So we can use that to check to see if newCard is in the array; if it isn’t, threeCards.indexOf(newCard) will equal -1.
  5. getting each of the chosen card’s image attributes and returning them to the DOM, with some basic styling written in CSS under the className of “card-picked”

Finally, we can’t forget to call the getThreeCards function within the return statement of our component, to render our cards in JSX to the DOM.

And finally, on click of a button, you will get your 3-card tarot spread on the screen! Much cheaper than a psychic. 😁