Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get which element I have clicked on? | React

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading