Home > Net >  How to get id from component in another component in functional components
How to get id from component in another component in functional components

Time:09-27

I'm new to react,

I'm trying to get a single card id from array of cards. I'm not getting how to do it.

My code looks like this.

card.js

import React from "react";

const cardDetailsClick = (ID) => {
    console.log("card id is "   ID);
};

const Card = ({ title, id }) => {
    return (
        <div className="card">
            <div className="description">
                <h1>{title}</h1>
                <button onClick={onBtnClick}>Know more</button>
            </div>
        </div>
    );
};

app.js -- here I want id of the card i click

import React from "react";
const [cards, setCards] = useState([]);
// I have setCards to be 20 different cards each has a unique id.
onBtnClick = (id) => {
    console.log(id); // I want the id of the card button I click here
};

const Cards = () => {
    return <div>{cards.length > 0 && cards.map((card) => <Card key={card.id} {...card} />)}</div>;
};

export default Cards;

I want to get the id of that card in which the button is clicked.

Help would be appreciated!

CodePudding user response:

Try this:

const cardDetailsClick = (e,ID) => {
    console.log("card id is "   ID);
};

const Card = ({ title, id }) => {
    return (
        <div className="card">
            <div className="description">
                <h1>{title}</h1>
                <button onClick={(e)=> onBtnClick(e,id)}>Know more</button>
            </div>
        </div>
    );
};
  • Related