React problem - returns empty string

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

function imageClicked(event) { 
  if (clicked.includes( === false) {
    setScore(score + 1); 
    } else {


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

And component fragment:

<div className="display">
       <img src={props.image} 
      /> <p>{}</p>  

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.


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(
    { className: "display"},
    React.createElement("img", { src: props.image, alt:, key:, onClick: props.onClick }),
    " ",
    React.createElement("p", null,

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 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.


This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.