Home  >  Q&A  >  body text

How to pass data to onclick function in loop in React.js?

<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粉523335026P粉523335026388 days ago472

reply all(2)I'll reply

  • P粉320361201

    P粉3203612012023-08-31 18:13:17

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

    reply
    0
  • P粉959676410

    P粉9596764102023-08-31 11:23:12

    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)

    reply
    0
  • Cancelreply