Basically I have a loop that runs through "ScannedCrops" and each scannedcrop renders with a button which says "View More". I want to pass the id (Which is stored in ScannedCrop._id) and console.log that onClick.
This is the loop
<div className={styles.scannedCropsGrid}>
{
scannedCrops.map(ScannedCrop => {
return <div>
<div className={styles.center}>
<div className={styles.scannedCropsContent}>
<img src={ScannedCrop.image} alt="/" />
<div className={`${ScannedCrop.healthyBoolean ? styles.healthyPlant : styles.notHealthy}`}>
{
<p>{ScannedCrop.healthyBoolean ? "Healthy" : "Not Healthy"}</p>
}
</div>
<div className={styles.healthDesc}>
<p>{ScannedCrop.healthyBoolean ? "No Disease" : ScannedCrop.diseaseName}</p>
<p>||</p>
<p>{ScannedCrop.dateTime}</p>
</div>
<div className={styles.center}>
<button className={styles.viewMoreBtn}>
More Info
</button>
</div>
</div>
</div>
</div>
})
}
</div>
This is the onClick function in the same component.
const getId = () => {
}
What I want to do is that onClick I want to get the ScannedCrop._id and console.log it. I am kind of a beginner at this.
CodePudding user response:
First of all you want to add a 'key' attribute to the parent in your map function. This can be either index
or the ScannedCrop._id
(if the later is always unique).
So it'll look like this:
...
{scannedCrops.map((ScannedCrop, index) => {
return <div key={index (or ScannedCrop._id if unique)} >
...
Lastly to answer your question, you first need to define your handler function and then pass it on to your button element inside the OnClick
event. It should end up looking like this:
//it is a common practice to name your functions
//'handleClick', 'handleOnView' and so on. You can name it
//whatever you want
const handleGetId = (id) => console.log(id)
...
<div className={styles.center}>
<button
onClick={() => handleGetId(ScannedCrop._id)}
className={styles.viewMoreBtn}>
More Info
</button>
</div>
...
Hope that answers your question!