onClick on dynamically created components React

0

I have a user-defined component called <Match> that is dynamically created inside another <Event> component. But putting an onClick on the component throws an exception. How to solve the problem, being that for each dynamically created component I need onClick which in the future will create a new component.

  

Events.js: 121 Uncaught TypeError: Can not read property 'addBetCard' of   undefined (...)

Event.js

  createMatch (match) {
    return <Match source={match} key={match.id} onClick={this.addBetCard.bind(this)}/>;
  }

  createMatches (matches) {
    return matches.map(this.createMatch);
  }

render() {

   return(
   ...
      <div className="ListMatches">
      {this.createMatches(dataFake)}
      </div>
)}

Temporary exit, how to improve?

My purpose is to have the onClick within the component <Match> and every time I click on the component call onClick of that component.

addBetCard(item){
    console.log("Adicionando item");
  }

createMatch (match) {
    return <a key={match.id} onClick={this.addBetCard.bind(this, match)}><Match source={match}/></a>;
}

createMatches (matches) {
    return matches.map((i) => this.createMatch(i));
    // return matches.map(this.createMatch);
}

render() {

   return(
   ...
      <div className="ListMatches">
      {this.createMatches(dataFake)}
      </div>
)}

The code snippet I just put up solves my problem, that when I click on the component it calls its onClick method. But it's an out-of-the-box exit where I need to put my <Match> component inside a <a> tag which in turn has onClick.

    
asked by anonymous 30.11.2016 / 14:54

1 answer

1

You have to fix the bindings , ie ensure that the execution context is correct.

You can do it like this:

constructor(props){
    super(props);
    this.addBetCard = this.addBetCard.bind(this);
    this.createMatch = this.createMatch.bind(this);
    this.createMatches = this.createMatches.bind(this);
}

createMatch (match) {
    return <Match source={match} key={match.id} onClick={this.addBetCard}/>;
}

createMatches (matches) {
    return matches.map(this.createMatch);
}

render() {
     // const dataFake = ['etc', 'etc'];
     return (
          // ...
          <div className="ListMatches">
          {this.createMatches(dataFake)}
          </div>
    )
}
    
01.12.2016 / 12:03