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