0

I'm trying to use switchHandler function inside this.state.persons.map() but getting

"Cannot read property 'switchHandler' of undefined" error

. However, if I'm using it outside the map function, it is accessible.

class App extends Component {
  state = {
    persons: [
      { name: "Max", age: 28 },
      { name: "Manu", age: 27, child: "My hobbies : racing" },
      { name: "Ron", age: 26 }
    ]
  };

  switchHandler = () => {
    this.setState({
      persons: [
        { name: "Maxii", age: 28 },
        { name: "Manu", age: 27, child: "My hobbies : swiming" },
        { name: "Ron", age: 26 }
      ]
    });
    //return "correct";
  };
  render() {
    //let obj = new App();
    return (
      <div className="App">
        <button onClick={this.switchHandler}>Switch Name</button>
        {this.state.persons.map(function(data) {
          return (
            <div>
              <Person
                clickChild={this.switchHandler}
                name={data.name}
                age={data.age}
              >
                {data.child}
              </Person> // // Here I'm getting error for switchHandler

            </div>
          );
        })}
        <Person name="tag" age="34" clickChild={this.switchHandler}>
          just
        </Person> // Here switchHandler is working fine


      </div>
    );
  }
}

export default App;

Error:

App.js:34 Uncaught TypeError: Cannot read property 'switchHandler' of undefined

Mikhail Zhuikov
  • 1,213
  • 2
  • 9
  • 19
Mrinal
  • 3
  • 2

1 Answers1

0

As your code is inside map's callback function, (this)context will be referred as this of call back function.

Where at other place, its in render function, and (this)context is correctly referred to component this.

Put below line in render function

const self = this;

and then refer self.switchHandler where this.switchHandler not working as below

clickChild={self.switchHandler}

Thanks

vipul patel
  • 668
  • 4
  • 7