Why can't I pass a function in the return body of the .map() function

78 views Asked by At

I am trying to learn how to code in react and I am following a tutorial. I've encountered a problem (Which I solved in another way) but would like to know how it works.

I have the following function before my render(){} method:

onDeleteHandler = () => {
  axios.delete('my_firebase_link'+this.props.obj.id+'.json')
  .then(console.log('Deleted'))
  .catch(err => console.log(err))

}

And in my render method, I tried to dynamically create a table row

render() {      
let tabRow = <p>Hello</p>;
if(this.state.businesses){
  tabRow = this.state.businesses.map(function(object, i){
    return <TableRow obj={object} key={i} onDelete={this.onDeleteHandler}/>;
  });
} return();

However, when I try to run that code, I get the following error: TypeError: Cannot read property 'onDeleteHandler' of undefined

After some searching for some tutorials, I ended up with the following code which works perfectly

render() {      
let tabRow = <p>Hello</p>;
if(this.state.businesses){
  tabRow = this.state.businesses.map(element =>(
    <TableRow obj={element} key={element.id} onDelete={(id) => this.onDeleteHandler(element.id)}/>
  ))
} return();

I would like to know why the last solution works, and why is it when I use the "function()" method inside the map, it throws an error.

Sorry if my explanation might be confusing but I will give any code if my explanation lacks it.

Thank you so much!

0

There are 0 answers