0

I add a click event inside loop of my react render method before return and the code as it follows

renderedCheckboxes = content.map( function(f, i) {
                if ( f['acf_fc_layout'] === 'checkbox' ) {
                    let id="customCheck" + i;
                    return (
                        <li className="list-group-item" key={i}>
                        <div className="custom-control custom-checkbox">
                            <input type="checkbox" name={f.checkbox} onClick={this.handleClick.bind(this) } className="custom-control-input" id={id} />
                            <label className="custom-control-label" htmlFor={id}>{f.label}</label>
                        </div>
                        </li>
                    )
                }
            });

but as I click on checkbox I get TypeError: Cannot read property 'handleClick' of undefined

What I do wrong in this case?

fefe
  • 8,755
  • 27
  • 104
  • 180
  • 1
    I susprect `this.handleClick` does not exists within the context of the map function. Cache this by writing `const that = this;` before the map function and use `that.handleClick` – Svdb Oct 16 '19 at 14:00
  • thanks! that was the problem was out of scope because map function – fefe Oct 16 '19 at 14:01
  • https://stackoverflow.com/questions/4886632/what-does-var-that-this-mean-in-javascript The accepted method is described as a hack that can be avoided by arrow functions. It will work, but is not the best practice. – Brian Thompson Oct 16 '19 at 14:19

2 Answers2

0

Change to arrow function so that this is in scope:

renderedCheckboxes = content.map((f, i) => {
  if ( f['acf_fc_layout'] === 'checkbox' ) {
    let id="customCheck" + i;
    return (
      <li className="list-group-item" key={i}>
        <div className="custom-control custom-checkbox">
          <input type="checkbox" name={f.checkbox} onClick={this.handleClick.bind(this) } className="custom-control-input" id={id} />
          <label className="custom-control-label" htmlFor={id}>{f.label}</label>
        </div>
      </li>
    )
  }
});
Brian Thompson
  • 13,263
  • 4
  • 23
  • 43
0

Your this.handleClick does not exists within the scrope of the map function. Cache this by writing const that = this; before the map function and use that.handleClick

Svdb
  • 337
  • 3
  • 14