Reputation: 508
I have a react component that I need to add an action when any of the cards in the group are clicked. The issue is I need to be able to identify which card was clicked to permform my action properly. Ive tried adding a key
and index
to each card but I cant figure out how to capture which card was clicked this is my code:
<>
<div className={styles.cardContainer}>
<div
className={`card-group ${styles.cardGroups}`}
>>>>> onClick={(e) => console.log(e.target)}
>
<Card index={type} className={styles.observationsType}>
<div className="">
<h2 className={styles.title}>{title}</h2>
<div className={styles.limits}>
{!!lim && !!lim.label.upper ? `Upper Limit: ${lim.label.upper}` : ""}
</div>
<div className={styles.limits}>
{!!lim && !!lim.label.lower ? `Lower Limit: ${lim.label.lower}` : ""}
</div>
</div>
</Card>
<Card index={type} className={styles.observationsDateCard}>
<div className={styles.date}>
<div>{!!obs.recordedDate && moment(obs.recordedDate).format("L")}</div>
<div>{!!obs.recordedDate && moment(obs.recordedDate).format("LT")}</div>
</div>
</Card>
<Card index={type} className={`text-center ${styles.observationLatest}`}>
<div className={styles.latest}>
{value}
<div>{obs.unit}</div>
</div>
</Card>
</div>
</div>
</>
You'll see in the card-group
div i have added the onClick
function with a console.log. And ive added an Index to each Card with the name of the group of information in each card in hopes of targeting that name. But this doesnt work. Is there anyway I can get to that property or a better way to go about doing this?
Upvotes: 0
Views: 825
Reputation: 539
Instead of rendering your cards as standalone components, try to store their data in an array and render the cards by using the map function. Then, you can give each card an onClick event with the index as a parameter, so you know which card is being clicked. Something like this:
Create an array of cards
const cards = [
{
name: "card 1",
// some other data
},
{
name: "card 2",
// some other data
},
{
name: "card 3",
// some other data
}
]
Create a function that captures the clicked card:
function onCardClick(index) {
const selectedCard = cards[index];
// do some stuff with the clicked card
}
Render the cards from the array:
{cards.map((card, index) => <Card onClick={() => onCardClick(index)} />)}
Upvotes: 1