How to pass data to onclick function in loop in React.js?
P粉523335026
2023-08-30 19:26:23
<p>First, I'll put in the code. </p>
<pre class="brush:php;toolbar:false;">{gameModes.map((gameMode, key) => {
return (
<>
<div className={styles.gameMode} key={key} onClick={gameModeHandler}>
<div className={styles.gameModeContent}>
<img src={gameMode.gameModeArtwork} alt="" />
<p className={styles.modeTitle}>{gameMode.gameModeTitle}</p>
<p className={styles.modeDesc}>
{gameMode.gameModeDesc}
</p>
</div>
</div>
</>
);
})}</pre>
<p><strong>onClick function</strong></p>
<pre class="brush:php;toolbar:false;">const gameModeHandler = (e) => {
console.log(e.target.value)
}</pre>
<p>Basically, what I want is, when onClick takes effect, pass the gameMode.title to the onClick function to print it to the console. I don't know how to pass onClick in a way that I can access that data in a loop. </p>
You need a second function to pass the data:
onClick={() => gameModeHandler(gameMode.title)}
.You need to use a callback function for your onClick event. and adjust your function accordingly;
onClick event
onClick function
However, if you wish to pass a single object from the loop to the called function, you can pass the gameMode object as a parameter to the gameModeHandler function;
onClick event
onClick function
Obviously you can then extract gameModeTitle;
from the object