0

Do you know why, when I invoke function outside of map it works, but not inside? I was trying to pass "this" in map's callback function argument. I trine to bind inline inside of map and nothing worked.

var React = require('react');
var PropTypes = require('prop-types');

class List extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      events: props.events
    };
    this.handleClick = this.handleClick.bind(this);
  }
  handleClick(e){
    console.log("Boom!")
  }
  render() {
    return (
      <div>
        <table onClick={this.handleClick}><tbody>
        {this.props.events.map(function(event){
               return(
                   <tr key={event.position}>
                   <td onClick={this.handleClick}>{event.position}</td>
                   <td>{event.start_time}</td>
                   <td>{event.duration}</td>
                   <td>{event.end_time}</td>
                   <td>{event.text}</td>
                   </tr>
               ) 
            })}
        </tbody></table>
      </div>
    )
  }
}
module.exports = List;

Please advise

1 Answer 1

1

Change it to a fat arrow function which makes this fall back to the outer scope. A function creates a new this when executed the way you're using it.

{this.props.events.map((event) => {
    ...
})}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot, that helped. It works even without binding in the constructor. I heard that fat arrow functions work differently. Is it possible to achieve the same not using it? I try to understand why binding didn't work this time. Trying to be clever one day :D
Yeah, that looks like making more sense than the things I tried to do. Thank You Bossman!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.