1

I'am trying to call a callback function in the parent, which is triggered inside the child component. I already tried the different ways of binding, but I still can't get it to work. I always get this error.

Cannot read property 'logMessage' of undefined

My Parent

logMessage() {
    console.log("logMessage was called");
  }

return(
      <div>
        <h1>Blogs</h1>
        {this.state.campaigns.map(function(blog) {
          return (
            <div key={blog._id}>
              <CampaignCard blog={blog} callBack={() => this.logMessage()} />
            </div>
          );
        })}
        <Link to="/campaigns/add">
          <button>Add Blog</button>
        </Link>
      </div>
    );

My child

  onConfirm={() => {
        this.setState({ show: false });
        this.props.callBack();
      }}

I can see that the callback function is called, but it still seems like this does not reference to the right place.

Giorgi Moniava
  • 27,046
  • 9
  • 53
  • 90
Fabio ha
  • 553
  • 1
  • 8
  • 29

4 Answers4

4
 {this.state.campaigns.map(function(blog) {
          return (
            <div key={blog._id}>
              <CampaignCard blog={blog} callBack={() => this.logMessage()} />
            </div>
          );
        })}

It is because it is inside map and for map you didn't use an arrow function. Because of that this refers to whatever this is inside map. Use something like:

render(){
let that = this;

.... // e.g. your map
    <CampaignCard blog={blog} callBack={() => that.logMessage()} />
...


}
Giorgi Moniava
  • 27,046
  • 9
  • 53
  • 90
2

Two of some options

logMessage = () => {
   console.log("logMessage was called");
}

or

constructor(props) {
   super(props);
   this.logMessage = this.logMessage.bind(this);
}
Ursus
  • 29,643
  • 3
  • 33
  • 50
2

Use an arrow function for your map:

{this.state.campaigns.map((blog) => {
          return (
            <div key={blog._id}>
              <CampaignCard blog={blog} callBack={() => this.logMessage()} />
            </div>
          );
        })}

Otherwise, this refers to the map callback context.

Davin Tryon
  • 66,517
  • 15
  • 143
  • 132
0

You need to bind the function in the parent:

constructor(props) {
    super(props);
    this.logMessage = this.logMessage.bind(this);
  }
Rodius
  • 2,271
  • 14
  • 19