0

Hi I have an array of cat images which I recovered from Giphy api.

enter image description here

What I want to do is click on the image and console.log the url associated with the image.

The below code is what I tried.

All that happen as soon as I hit the search button console.log showed 25 undefined items.

So I think i'm passing information wrong, and it's detecting onCLick outside of the div

enter image description here

import React from "react";

function handleClick(props) {
  console.log(props.gif);
}

const UserItem = props => {
  return (
    <div className="column">
      <img
        onClick={handleClick(props.gif)}
        alt=""
        src={props.gif}
        className="ui image"
      />
    </div>
  );
};

export default UserItem;
Community
  • 1
  • 1
Jay
  • 185
  • 15

1 Answers1

2

You have a minor mistake, pay attention that onClick prop accepts a "pointer" to a function, in your code, you are invoking handleClick and it returns undefined, therefore, your code is not working.

You can change your handler to get the clicked element src attribute by accessing the click event.

import React from "react";

function handleClick(event) {
  console.log(event.target.src);
}

const UserItem = props => {
  return (
    <div className="column">
      <img
        onClick={handleClick}
        alt=""
        src={props.gif}
        className="ui image"
      />
    </div>
  );
};

export default UserItem;
felixmosh
  • 32,615
  • 9
  • 69
  • 88