Reputation: 46529
I am trying to add an on click function to my list tags that are mapped from an array, i.e:
{this.props.addresses.map((address, index) =>
<li key={`address-${index}`} onClick={this.addressClick}>{address.prediction}</li>
)}
addressClick is defined in constructor like this:
constructor (props) {
super(props)
this.addressClick = this.addressClick.bind(this)
}
and as a function in the class like this
addressClick () {
console.log('Clicked')
}
When I click on my list tag nothing happens, I don't see any console statements.
Upvotes: 1
Views: 34
Reputation: 137
Your code should work unless I am missing something. This works for example:
const arr = [1,2,3,4]
class App extends Component {
constructor(props) {
super(props)
this.addressClick = this.addressClick.bind(this)
}
addressClick () {
console.log('Clicked')
}
render() {
return (
<ul>
{arr.map((address, index) =>
<li key={`address-${index}`} onClick={this.addressClick}>{address}</li>
) }
</ul>
)
}
}
Upvotes: 0
Reputation: 21856
Bind this to the map method:
{this.props.addresses.map((address, index) =>
<li key={`address-${index}`} onClick={this.addressClick}>{address.prediction}</li>
).bind(this)}
Upvotes: 2
Reputation: 825
You can implement this by passing the index to another function and then call addressClick()
.
function clickListener ( index ) {
var clickedAddress = addresses[index];
addressClick(clickedAddress.prediction);
}
{this.props.addresses.map((address, index) =>
<li key={`address-${index}`} onClick={`clickListener(${index})`}</li>
)}
Upvotes: 0