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