I render 12 cards on the screen each of which have a unique key attribute.
I only started learning react and I want function to only to be called when a card has been clicked and save only that key which been clicked in state if an other has been clicked then update the state and then have 2 ids there and not all 12.
This is my Card component (the others are irrelevant I think)
import React, {useState} from "react";
import {CardData} from "./Data/CardsData.js"
import style from "../style/Cards.css"
import Score from "./Score.js";
const Cards = () =>{
const [bestScore, setBestScore] = useState(0);
const [scoreRN, setScoreRN] = useState(0);
const [clickedCard, setClickedCard] =useState([]);
const CardClick = () =>{
for(let card of CardData)
setClickedCard( clickedCard.concat(card))
console.log(clickedCard)
}
return(
<div id="content">
<Score bestScore={bestScore} scoreRN={scoreRN}/>
{CardData.map((data) => {
return(
<div key={data.id} className="card" onClick={CardClick}>
<img src={data.img}></img>
<h2>{data.name}</h2>
</div>
)
})}
</div>
)
}
export default Cards;
This way I only get the last card's id into my clickedCard array, every time I click on a card.
I have also could do it where I added every cardid on every click.
And an additional thing that I don't fully understand: Why is it that now the 1. console log is returns an empty array (then 1, 2,3 ... elemement)?
CodePudding user response:
CardClick
callback is a MouseEventHandler
so it receives event
as first argument.
You can then get event.currentTarget.id
in the CardClick
function (if your element has an id
)
Another way is to explicit pass data to the onClick
handler like onClick={event => CardClick(event, data.id)}
. Then your CardClick
function can accept your aditionnal arguments
CodePudding user response:
You don't need the for loop if you just want to add the clicked card into the array, but you do need to pass a card
parameter so that the callback knows which card was clicked:
const CardClick = (card) =>{
// for(let card of CardData) - you can remove this line
setClickedCard( clickedCard.concat(card))
console.log(clickedCard)
}
In your JSX:
<div key={data.id} className="card" onClick={() => CardClick(data)}>
<img src={data.img}></img>
<h2>{data.name}</h2>
</div>
Also, your console.log
is returning an empty array because react state changes aren't immediate, so even after you called setClickedCard
, clickedCard
will still be its old value in the same function until React's next render.