Home > OS >  React: how to use onclick function in a loop in class component?
React: how to use onclick function in a loop in class component?

Time:02-12

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.

CodePudding user response:

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

CodePudding user response:

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;

CodePudding user response:

Try this:

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

  • Related