user3209048 user3209048 - 1 month ago 18
React JSX Question

attach onClick handler to populated list item reactjs

i have a function that i want to fire when a button is being clicked, this button is included in a list item that gets populated based on values from an array passed from the parent component, but its not working and returning an error saying that the function is undefined, how can i make this work?

import React from 'react';

export default class Card extends React.Component {

constructor(){
super()
this.state = {
index: null
};
}

handleClick(x){
this.setState({
index: x
})

}

render(){
/**
* Populates list items according to data passed
* on to resultsArray.
*/
var items = this.props.resultsArray;
var itemslist = items.map(function(item, index){
return(
<li key={ index } class="card" >
<div class="card-header">
<span class="hour-price"><span>{ item.hourPrice } &euro; /hour</span></span>
<img src={ item.image } class="card-img" />
<a href="javascript:" onClick={this.handleClick.bind(this, {index})} class="book-button">Book</a>
</div>
<div>
<div class="card-info">
<p class="workplace-name">{ item.name }</p>
<span class="score">{ item.score } &#9733;</span>
<p class="location">{ item.location }</p>
</div>
<div class="card-footer">
<p class="price">{ item.price } &euro; / Day</p>
</div>
</div>
</li>
);})
return(
<div class="results-container">
<ul class="card-list center">
{ itemslist }
</ul>
</div>
);

}
}

Answer

You should change your render to the below codes. Use that instead of this.

var items = this.props.resultsArray;
var that = this;
var itemslist = items.map(function(item, index){
      return(
          <li key={ index } class="card" >
            <div class="card-header">
                <span class="hour-price"><span>{ item.hourPrice } &euro; /hour</span></span>
                <img src={ item.image } class="card-img" />
                <a href="javascript:" onClick={that.handleClick.bind(that, {index})} class="book-button">Book</a>
            </div>
           ......