How to pass data to onclick function in loop in React.js?
P粉523335026
P粉523335026 2023-08-30 19:26:23
0
2
507
<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>
P粉523335026
P粉523335026

reply all(2)
P粉320361201

You need a second function to pass the data: onClick={() => gameModeHandler(gameMode.title)}.

P粉959676410

You need to use a callback function for your onClick event. and adjust your function accordingly;

onClick event

onClick={()=>gameModeHandler(gameMode.gameModeTitle)}

onClick function

const gameModeHandler = (gameModeTitle) => {
    console.log(gameModeTitle)
  }

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={()=>gameModeHandler(gameMode)}

onClick function

const gameModeHandler = (gameMode) => {
    console.log(gameMode)
  }

Obviously you can then extract gameModeTitle;

from the object
console.log(gameMode.gameModeTitle)
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!