简体   繁体   中英

Can't get id of element with e.target.value

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

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 .

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.

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" onClick={props.onClick}>
      <div className="img-container">
        <img src={props.image} id={props.id} 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM