0

I don't know why but I cannot set an onClick function for a function from the parent that I want to pass to my child component. This is the code from the parent:

_renderChatFriend() {
    return([...this.state.friendsNames].map( friend => {
      return (<ChatFriendPopUp 
          onChatFriendPopUpClick={this.popUpMessage} 
          key={friend.id} 
          name={friend.name} 
        />)
    }))
  }

and the code on the child component:

class ChatFriendPopUp extends Component {
  popUpMessage(name) {
    console.log("name clicked ",name)
  }
  render() {
    return (
        <li  onClick={this.props.onChatFriendPopUpClick(this.props.name)}>{this.props.name}</li>
    )
  }
}

The onClick is invoked upon mount? and when I click it's not invoked? but I can invoke it by onClick if I don't pass an argument on it. A code like this but I cannot have referrence:

<li  onClick={this.props.onChatFriendPopUpClick}> // not passing argument works?
2
  • 1
    You're calling it-not sure what you expect. Are you actually asking how to use it but pass a parameter? Commented Aug 9, 2017 at 14:41
  • Possible duplicate of Reactjs Audio button? Commented Aug 9, 2017 at 14:46

1 Answer 1

6

You have to add it as a callback function otherwise it will get called immediately. Change it to this

 <li onClick={() => this.props.onChatFriendPopUpClick(this.props.name)}>{this.props.name}</li>
Sign up to request clarification or add additional context in comments.

2 Comments

do you have some links so I can read more on this? it works but I feel like missing something
@iamnewbie The React Tutorials are a nice start, but that one is JavaScript specific. facebook.github.io/react/docs/handling-events.html

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.