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
id
does not exist yet. You could define it outside and use the variable for both props, or use the same calculation :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.
or if you want access to this keyword then,
example:
You can use the
ref
attribute of the component.You could also extract an
Img
component for reuse:Demo