Search code examples
reactjsdictionaryonchange

React this.onChange() is not calling inside map function


i am getting the following error when i use to call onChange function inside map method

Uncaught TypeError: Cannot read property 'onCheckChange' of undefined at onChange

my code is following

  getPlanCheckbox(jsonParseservicelist, bbuserid) {
        const returnresult = jsonParseservicelist.map(function (single) {
          return (
            <div className="">
              <label className="" >
                <input type="checkbox" onChange={() => this.onCheckChange(bbuserid, single.plantype)} defaultChecked={single.isActive == 1 ? "checked" : ""} />
                <span className="" />
              </label>
            </div>);
        });
        return returnresult;
      }



    onCheckChange = (e, bbuid, plantype) => {
        console.log(bbuid, plantype);

      }

Solution

  • i try this and i found 2 solution

    1st is just replaced your function with following

    getPlanCheckbox(jsonParseservicelist, bbuserid) {
        var self = this;
        const returnresult = jsonParseservicelist.map(function (single) {
          return (
            <div className="">
              <label className="" >
                <input type="checkbox" onChange={() => self.onCheckChange(bbuserid, single.plantype)} defaultChecked={single.isActive == 1 ? "checked" : ""} />
                <span className="" />
              </label>
            </div>);
        });
        return returnresult;
      }
    

    just take this inside another variable and the user that variable name to call function lets say

    var self = this;
    

    now i use self to call the function like this

    self.onCheckChange();
    

    and 2nd is use map as arrow function

    data.map((single) => {
    })