I'm trying to grab the id of the element that's being clicked so I can use that id parameter to grab the selected product data with an api call.
When I used an onClick handler to grab it with the e.target.id I get nothing.
Is this not the right approach to get an individual item by id?
here's my sandbox https://codesandbox.io/s/filter-test-forked-wli18?file=/src/App.js
CodePudding user response:
First of all, in your Card component, you have:
<div className="card" onClick={props.onClick}>
But in App.js
, you use handleClick
property when you call Card
component. Instead, it should be:
<Card
onClick={handleClick}
/>
Next, the Event
object parameter is native JS event, it does not contain any of the React props. To access clicked card id
in event handler, you would have to do something like this:
<div className="card" onClick={e => props.onClick(e, props.id)}>
This way, you would have access to the Event
object and to card item id
.
CodePudding user response:
First of all your handleClick function is not being executed. to execute the function you need to change onClick={props.onClick}
to onClick={props.handleClick}
in line no 5 of card.js file. Then the handleClick function will be triggered.
CodePudding user response:
Your card component does not have id set. In your card component, set the id passed through props like this
export default function Card(props) {
return (
<div className="card" id={props.id} onClick={props.onClick}>
<div className="img-container">
<img src={props.image} alt={props.id} />
</div>
<div className="info">
<p className="info-title">
<span>
<a href={props.url}>{props.title}...</a>
</span>
</p>
<p style={{ textAlign: "center" }}> {props.price} </p>
</div>
</div>
);
}
And then, in your App.js, use your card component like this to call handleChange
<Card
id={item.id}
key={item.id}
title={item.title}
image={item.image}
price={item.price}
onClick={(e) => handleClick(e)}
/>
You will get the element you clicked in console.log.