0
votes

In my react component where I try to render a list based on material-ui List component, I have the following problem.

I loop through an array of contact objects to render a list of ListItem, but I want to be able to handle click event on each List item.

I use the onTouchTap prop and tries to call my onSelectedContact method but how do I pass in the current contact object from the map function?

{this.props.contacts.map(( contact, i ) => <span key={i}>
  <ListItem
    key={i}
    primaryText={contact.name}
    onTouchTap={this.onSelectContact?????}
  />
}
1
this.onSelectContact.bind(this, contact)Maxx
@Maxx that's not a comment, that's an answer.Ven
bind creates new function with given context and params. first parameter is context, others are parametersMaxx
@anoop you need bind here in 2 cases. 1 to just bind some params to function (as in question), 2 to bind context. there is a mistake in your example (onTouchTap={onSelectContact()}). You execute function and pass its result. Right is onTouchTap={onSelectContact} you pass just handler. When ListItem does this.props.onTouchTap() its changes its context, it means you can't (for example) do this.setState() in parent component handler because context in handler is ListItem's props object. Sry for my english )Maxx
@anoop 1. you should not declare functions at render function (it declares at every render), 2. You have a stateless components in your example it means you can't use component's state. What your handler gonna do in real world code?Maxx

1 Answers

2
votes

this.onSelectContact.bind(this, contact)