I am completely stuck on my current project. I’m building a card memory game in React. Most of the front end is complete and able to flip the cards to guess what’s on the back.
When you click on 2 cards and they don’t match, they automatically flip face down. This part works. However when I attempt to flip the same 2 cards, only one flips. The other one I have to click twice.
I inserted console.log before the automatic flipping and after and it appears that state
isn’t being toggled. So I used setState()
right after the cards automatically flipped over, but doesn’t do anything.
I was wondering if someone had any free time to go over this with me on zoom and try to solve it?
Here is a link to the repository if you wanna check it out:
You just need to install the font awesome package dependency. Below are my 2 components Card.js
and App.js
.
App.js
import React, { Component } from "react"
import "../assets/css/App.css"
import { faOtter,faHippo,faDog,faSpider,faHorse,faFrog,faFish,faCat,faDragon,faDove }
from '@fortawesome/free-solid-svg-icons'
import Card from "./Card";
const icons = [
faOtter,
faHippo,
faDog,
faSpider,
faHorse,
faFrog,
faFish,
faCat,
faDragon,
faDove,
faOtter,
faHippo,
faDog,
faSpider,
faHorse,
faFrog,
faFish,
faCat,
faDragon,
faDove,
]
class App extends Component {
render() {
// const zeros = new Array(20).fill(0)
// const cards = zeros.map((zero, index) => (<Card />))
let cards = icons.map((icon, index) => (<Card icon={ icon } key={Number(index)} id={ index } />))
return (
<>
<h3>Welcome!!</h3>
<div className="cards-container">
{ cards }
</div>
</>
);
}
}
export default App;
Card.js
import React, { Component } from "react";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
let selectedCards = [];
class Card extends Component {
constructor(props) {
super(props);
this.state = {
isFlipped: false,
}
}
toggleClass = (event) => {
selectedCards.push(event.currentTarget.id)
if (selectedCards.length === 2) {
var card1 = document.getElementsByClassName(selectedCards[0])[0]
var card2 = document.getElementsByClassName(selectedCards[1])[0]
console.log(this.state.isFlipped)
setTimeout(() => {
card1.classList.remove('is-flipped')
card2.classList.remove('is-flipped')
this.setState((prevState) => ({ isFlipped: !prevState.isFlipped }))
console.log(this.state.isFlipped)
}, 1000)
selectedCards = []
}
this.setState((prevState) => ({ isFlipped: !prevState.isFlipped }))
}
render() {
return (
<div className="fade-in scene" }>
<div
className={
this.state.isFlipped
? `card is-flipped ${this.props.id}`
: `card ${this.props.id}`
}
onClick={this.toggleClass}
id={this.props.id}
>
<div
className="card__face card__face--front"
></div>
<div className="card__face card__face--back">
<FontAwesomeIcon icon={this.props.icon} color="coral" size="2x" />
</div>
</div>
</div>
);
}
}
export default Card;