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

267
Visualizações
React: how to use onclick function in a loop in class component?

what i want is to run an onClick event handler in a loop. what i have done is :

my component looks something like this.

import React, { Component } from "react";
import Link from 'next/link';

class VehicleSpecifications extends Component {

constructor(props) {
super(props);
this.setActiveClass = this.setActiveClass.bind(this)

this.state = {
    tabStatus: "",
};
}


setActiveClass = (e) => {
  console.log(e)
}

render() {
const vehicleSpecs = this.props.vehicleSpecs;
console.log(this.props.vehicleSpecs)
return (
  <React.Fragment>
    <div className="vertical-tabs" >
      <ul className="nav nav-tabs" role="tablist">
        {
          Object.entries(vehicleSpecs).map(function (items, car_index) {
            let typeAndName = items[0].split(':-:');
            return (
              <li className="nav-item"   onClick={ ()=> setActiveClass("#pag") }>
                <Link
                  className="nav-link active"
                  data-toggle="tab"
                  href={"#pag" + car_index}
                  role="tab"
                  aria-controls="performance">
                  {typeAndName[0].replace('_', ' ').toUpperCase()}
                  
                </Link>
              </li>
            )
          })
        }
      </ul>
     
    </div>
  </React.Fragment>
);
}
}

export default VehicleSpecifications;

i have tried things but this onclick function sometime gives _this is undefined or says function is undefined.

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

0

Try this:

onClick={ ()=> { this.setActiveClass("#pag") }}

about 4 years ago · Juan Pablo Isaza Relatório

0

You're in a class component, so onClick={ () => this.setActiveClass("#pag") } otherwise setActiveClass is not defined in render scope

about 4 years ago · Juan Pablo Isaza Relatório

0

Here check this out I created a simple example for you.

since you are using the arrow function inside onClick you don't need to do the binding inside the constructor;

Check the example code below,

or open this codesandbox link to see it live

import { Component } from "react";

const seed = ["Matt", "Jake", "Ross", "Michale"];

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      tab: ""
    };
  }

  // setSomeState = (label) => {
  //   console.log(label);
  //   this.setState({ tab: label });
  // };

 
  // Doesn't matter what type of this function is

  setSomeState(label) {
    console.log(label);
    this.setState({ tab: label });
  }

  render() {
    const { tab } = this.state;
    return (
      <div style={{ fontFamily: "sans-serif", textAlign: "center" }}>
        <h1>{tab ? tab : "No Value Selected"}</h1>
        {seed.map((label, index) => (
          <h2
            key={`${label} ${index}`}
            onClick={() => this.setSomeState(label)}
            style={{
              background: "#efefef",
              padding: "20px",
              cursor: "pointer"
            }}
          >
            {label}
          </h2>
        ))}
      </div>
    );
  }
}

export default App;
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