0

In my react app, I have an onClick function that isn't being recognized (TypeError: _this2.click is not a function) when called from dynamically-generated components. I poked around for issues with functions not being bound correctly, but they seem to be. Here's the code:

class C extends React.Component {

  constructor(props) {
    super(props);


    // Bind components
    this.eventComponent = this.eventComponent.bind(this);
    this.click = this.click(this);
  }

  /**
   * Click function for when a user selects their choice
   * @param  {[int]} id [id of the event the user is selecting]
   */
  click(id) {
    console.log(id)
  }

  /**
   * Draws an event component (dynamically generated)
   * @param  {[String]} name    [name of the event]
   * @param  {[String]} summary [summary of event]
   * @return {[Object]}         [react element of an event]
   */
  eventComponent(name, summary, id) {
    if (name != null && summary != null) {
      return (
        <div >
          <h1>{name}</h1>
          <p>{summary}</p>
          <button onClick={() => this.click(id)}>Here is a button!</button>
        </div>
        );
    }

  }


  render() {

    var event = this.state.event

    var objArray = this.state.objArray

    var eventMap;

    if (event) {
      eventMap = objArray.map(function(event) {
        // Get first property
        var firstProp;
        var k;
        for(var key in event) {
            if(event.hasOwnProperty(key)) {
                firstProp = event[key];
                k = key;
                break;
            }
        }
        return this.eventComponent(firstProp.title, firstProp.summary, k);
      }.bind(this))
    } else {
      eventMap = <p>No events found!</p>;
    }

    // Generate a default HTML object
    var eventComponent = (
      <div>
          {eventMap}
      </div>
    );

    return eventComponent;
  }

}
1
  • 1
    It should be this.click.bind(this); Commented Dec 25, 2018 at 17:58

3 Answers 3

5

in your constructor correct this this.click = this.click(this); to this.click = this.click.bind(this);

1

The most easy and convenient way is to use arrow functions, so you don't need to do binding in constructor anymore, a lot easier, isn't it?

so just remove this from constructor:

this.click = this.click.bind(this);

and change your function to:

click = (id) => {
    console.log(id)
  }
1

As answered by Vikas, either you can follow that approach or you can use arrow syntax for functions using which there will be no need to bind functions. Eg. Click = (Id) => {

} .

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.