Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

268
Vistas
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 Respuestas
Responde la pregunta

0

Try this:

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

about 4 years ago · Juan Pablo Isaza Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda