Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

257
Visualizações
How to pass the key used from JSON response objects in a map as a parameter for onclick() function in React?

I have tried to create a list of 'League' objects from the server, the user can click to create a league successfully, but to join a league the user will need to click the icon and the parameter will need to be sent to the joinLeague() function as the league.leagueId is required to join the league by the API:

LeagueList component:

 constructor(props) {
    super(props);
    this.state = {
        leagues: []
    };

    this.createLeague = this.createLeague.bind(this);

    this.joinLeague = this.joinLeague.bind(this);
}

 joinLeague() {
    const payload = {
        "username": localStorage.getItem("username"),
        "leagueId":
    };
    fetch(JOIN_LEAGUE_URL, {
        method: 'POST',
        headers: {
            "Accept": "application/json",
            "Content-Type": "application/json",
            "Authorization": localStorage.getItem("token")
        },
        body: JSON.stringify(payload)
    })
        .then(response => response.json())
        .then();
}

   render() {
        const {leagues} = this.state;

    const leagueList = leagues.map(league => {
        return <tr key={league.leagueId}>
            <td style={{whiteSpace: 'nowrap'}}>{league.leagueCreatorUsername}</td>
            <td>{league.playerCount}/10</td>
            <td>{league.matchesPerPlayer}</td>
            <td>{league.numberOfGamesPlayed}</td>
            <td>{league.totalGamesToBePlayed}</td>
            <i className="fas fa-plus" onClick={this.joinLeague}></i>
        </tr>
    });

}

In the joinLeague() function above you can see I am trying to create the payload but I need the leagueId from the as a parameter.

How can I accomplish this? I have tried {this.joinLeague.bind(league)} but it didn't work, thanks.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

If you use an arrow function, it should bind itself to the scope (keeping the current value of league)

You could try something like this?

render() {
  const {leagues} = this.state;

  const leagueList = leagues.map(league => {
    return <tr key={league.leagueId}>
      <td style={{whiteSpace: 'nowrap'}}>{league.leagueCreatorUsername}</td>
      <td>{league.playerCount}/10</td>
      <td>{league.matchesPerPlayer}</td>
      <td>{league.numberOfGamesPlayed}</td>
      <td>{league.totalGamesToBePlayed}</td>
      <i className="fas fa-plus" onClick={() => this.joinLeague(league.leagueId)}></i>
    </tr>
  });
}

joinLeague(leagueId) {
    const payload = {
        "username": localStorage.getItem("username"),
        "leagueId": leagueId
    };
    fetch(JOIN_LEAGUE_URL, {
    ...

Here is a link to a minimal example, showing that the leagueId is now available in joinLeague

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda