skip to Main Content

I am making a memory game and I want to pass the id of the img with the OnClick value to then store it

 <img src={OYOOO} alt={`Image ${i + 2}`} id = {i * 4 - 1} onClick={() => imageClick(id)}/>

The imageClick function is built like this :

function imageClick(value){
alert("Test");
alert(value)}

However, react can’t see what I am actually trying to pass, and I get a "id is not defined" error. The id is coming from a loop where I declare a lot of imgs (16) to make a square of img.

3

Answers


  1. id does not exist yet. You could define it outside and use the variable for both props, or use the same calculation :

    <img src={OYOOO} alt={`Image ${i + 2}`} id = {i * 4 - 1} onClick={() => imageClick(i * 4 -1)}/>
    
    Login or Signup to reply.
  2. It would be helpful if you provide where the id is coming from?

    but you can use bind method to preconfigure the function with argument.

    <img src={OYOOO} onClick={imageClick.bind(null, id)}/>
    

    or if you want access to this keyword then,

    <img src={OYOOO} onClick={imageClick.bind(this, id)}/>
    

    example:

    [{id: 1, src: 'url'},{id: 2, src: 'url'},{id: 3, src: 'url'}].map((image) => {
    return <img key={image.id} src={image.src} onClick={imageClick.bind(null, image.id)/>
    })
    
    Login or Signup to reply.
  3. You can use the ref attribute of the component.

    import { FC, useRef } from 'react';
    
    export const App: FC<{ name: string }> = ({ name }) => {
      const img = useRef<HTMLImageElement>(null);
    
      return (
        <div>
          <img src="https://fakeimg.pl/300" ref={img} id="0835012b-e5e7-42ad-9f85-8222be2583d1" onClick={() => {
            console.log('Image ID: ', img.current.id);
          }} />
        </div>
      );
    };
    

    You could also extract an Img component for reuse:

    import { FC, useRef } from 'react';
    import { v4 as uuid } from 'uuid';
    
    export const Img: FC = () => {
      const img = useRef<HTMLImageElement>(null);
    
      return (
        <img
          src="https://fakeimg.pl/300"
          ref={img}
          id={uuid()}
          onClick={() => {
            console.log('Image ID: ', img.current.id);
          }}
        />
      );
    };
    
    export const App: FC = () => {
      return (
        <div>
          <Img />
          <Img />
        </div>
      );
    };
    

    Demo

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search