-1

I have a jsx file, which creates <li> elements on page load. These <li> items are created based on the ajax return values.

For each <li> element i am adding "click" event programatically, which calls a react function (friendChat) . But while implementing this, i am getting the following error. (But i am able to get other properties. which initialised inside constructor.)

  • Error:this.friendChat is not a function

Following is my jsx file.

Thanks in advance.

jsx file

import React from 'react'

class Home extends React.Component {


constructor(props) {

    super(props);
    this.state = {username: "Anu"};
    this.friendChat = this.friendChat.bind(this);


  }


  friendChat(friendId)
  {
        console.log("Clicked friend id: "+ friendId );

  }





componentDidMount() {
     console.log('Component DID MOUNT!');


 $(document).ready(function(){


     $.ajax({
        type: "GET",
        url: "/friends/myFriends",
        success: function(data){

          if (data == "No friends")
            {
                 console.log("No friends exist");
                document.getElementById('friends').innerHTML = "Please add 
   friends";
             }
            else
            {
            console.log("Friends: "+data);
             //Displaying friends in div
             for (var i = 0; i < data.length; i++) 
              {
                  console.log("Friend: "+ data[i]);
                 var li=document.createElement("li");
                 //var br=document.createElement("br");
                 li.appendChild(document.createTextNode(data[i]));
                 li.setAttribute("id",data[i]);


                console.log(this.state.username);
           //It's Printing correctusername (Anu) initialised inside 
            //the constructor


                //Adding on click event for each friend

               li.addEventListener("click", function() { 
               this.friendChat(this.id); }, false);
               //Here it's showing the error of this.friendChat is not a 
               //function

             //Appending list item to document
             document.getElementById("friends").appendChild(li);
          }
        }


    }.bind(this)
 });


 }



 render() {
   return (


  <div>



        <div className="home_recentfriends">
           <ul id="friends"></ul>
        </div>


  </div>


   )
   }


 }

 export default Home
abhilash
  • 1
  • 1
  • Possible duplicate of [How to access the correct \`this\` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – Andrew Li Aug 29 '17 at 01:23
  • Why you are using javascript pure in ajax jquery request if you use jquery, follow using jquery but don't use jquery and javascript in same function, this cause errors like yours – Risa__B Aug 29 '17 at 01:26
  • It explained very well.Thanks @Andrew Li. – abhilash Aug 29 '17 at 02:37
  • And i got exact answer from @Giovanni Lobitos – abhilash Aug 29 '17 at 02:37
  • @abhilash If the duplicate helped, please accept the duplicate by clicking the yellow banner above the question. – Andrew Li Aug 29 '17 at 02:39

1 Answers1

1

Solution 1: Transform all your functions inside that method into fat-arrow and everything will work.

Example:

$(document).ready(function(){...})

Change into:

$(document).ready(()=>{...})

Solution 2: Store the reference of the this keyword into a variable and access that variable instead.

Example:

componentDidMount() {
 const self = this;

 ....

 self.friendChat(self.id);

}
Giovanni Lobitos
  • 852
  • 7
  • 19