getting this is undefined Error at React JS

Viewed 42

I am always getting this is undefined error at react although i dont know how to solve this

{this.state.persons.map(function (person) {
  return (
      <tr data-testid="article" key="article-index">
          <td data-testid="article-firstName" id="personID">{person.id}</td>
          <td data-testid="article-firstName">{person.firstName}</td>
          <td data-testid="article-lastName">{person.lastName}</td>
          <td data-testid="article-lastName">{person.age}</td>
          <td data-testid="article-email">{person.email}</td>
          <button className="small" onClick={this.updatePerson}>Search</button>
          <td><button className="btn btn-danger small">Delete</button></td>
      </tr>
  )
})}          

Here I add A Event Listener onClick={this.updatePerson}

and this is my constructor

constructor(props) {
  super(props);
  this.state = {
      persons: this.props.persons
  }
  this.updatePerson = this.updatePerson.bind(this);
}

And Here is my update Function

updatePerson() {
  console.log("Updated Person");
}

But Every time iam running this its giving me a error

this is undefined

enter image description here

1 Answers

Try to use arrow function

{this.state.persons.map((person) => {
    return (
        <tr data-testid="article" key="article-index">
            <td data-testid="article-firstName" id="personID">{person.id}</td>
            <td data-testid="article-firstName">{person.firstName}</td>
            <td data-testid="article-lastName">{person.lastName}</td>
            <td data-testid="article-lastName">{person.age}</td>
            <td data-testid="article-email">{person.email}</td>
            <button className="small" onClick={this.updatePerson}>Search</button>
            <td><button className="btn btn-danger small">Delete</button></td>
        </tr>
    )
})} 
Related