React problem - event.target.key returns empty string

Hello I have a problem with returning an id value (defined in the key attribute) of the image when using event.target.

function imageClicked(event) { 
  console.log(event.target.key); 
  setClicked(event.target.key);
  shuffle(GameData);  
  if (clicked.includes(event.target.key) === false) {
    setScore(score + 1); 
    setClicked([...clicked, event.target.key]);  
    } else {
       setScore(0);
       setClicked([]);
     } 
  } 

 ...  

 <Display onClick={imageClicked} items={GameData} />  

And component fragment:

<div className="display">
       <img src={props.image} 
        alt={props.name} 
        key={props.id} 
        onClick={props.onClick} 
      /> <p>{props.name}</p>  
   </div> 

However when I am using an alt attribute of the image the app works as intended. But I want to change it anyway as I creacted ids for all images and they are currently unused.

Thanks in advance.

Here is the link to the full app (using alt attribute) in CodeSandbox.

IMG elements don’t have a “key” attribute (no HTML element does, it’s not a thing), so you’re trying to target an attribute that doesn’t exist; your code can’t find it because it isn’t there. If you want to select by ID, why aren’t you using the “id” attribute that every HTML element has? You can’t just add arbitrary attributes to HTML, each element has a specific, defined set of attributes it can have.

2 Likes

I would define the click event handler at card level and pass down the setClicked instead. That way you can use the component’s id prop in the event handler directly.

1 Like

Thanks for an answer. I managed to correct this using id attribute as you suggested.
I also added corresponding props in the Display and Card components.

1 Like

Thanks for an answer. In the other comment I wrote how I corrected this.

1 Like

Just to be clear, the JSX code you have written is this:

function TheJsxComponentFragmentYouPosted (props) {
  return React.createElement(
    "div",
    { className: "display"},
    React.createElement("img", { src: props.image, alt: props.name, key: props.id, onClick: props.onClick }),
    " ",
    React.createElement("p", null, props.name)
  );
}

JSX is just a way of writing JS functions in XML so that they look like HTML. JSX is not HTML. When you run that callback, you are using event.target to target the DOM element that triggered the event. That is a DOM element, and it only has actual properties that exist on DOM elements. key is just an argument given to one of those React.createElement functions.

2 Likes