Home > Mobile >  How do I pass the data in a loop to an onclick (React.js)
How do I pass the data in a loop to an onclick (React.js)

Time:12-02

I will put in the code first.

{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>
              </>
            );
          })}

The onClick function

const gameModeHandler = (e) => {
    console.log(e.target.value)
  }

Basically what I want is, when the onClick takes effect it passes in the gameMode.title to the onClick to console.log it. I do not know how to pass the onClick in a way where it has access to that data in the loop.

CodePudding user response:

You would have to use a callback function for your onClick event. And adjust your function thus;

The onClick event

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

The onClick function

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

However, if you wish to pass a single object from your loop to the invoked function, you may just pass the gameMode object as an argument to the gameModeHandler function thus;

The onClick event

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

The onClick function

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

Apparently, you can subsequently extract the gameModeTitle from the object thus;

console.log(gameMode.gameModeTitle)

CodePudding user response:

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

  • Related