StochasticNerd StochasticNerd - 10 days ago 5
React JSX Question

Handling click event in React

I'm rendering a list of images in my React component,

render() {
return (
<div>
<ul className="list-inline">
{this.props.images.map(this.displayListOfImages)}
</ul>

</div>

);

}


This is the function that renders the jsx

displayListOfImages(image, index) {
return (
<li key={index}>
<a href="#" onClick={this.handleImageClick}>
<div className="img-wrapper">
<div className="img" style={{backgroundImage: `url(${image.src})`}}></div>
<div className="img-selector">
<span className="glyphicon-plus" id="plus-icon" aria-hidden="true"></span>
</div>
</div>

</a>
</li>
);
}


I'm using the function handleImageClick to get the image that was clicked on,

handleImageClick(event,image){
event.preventDefault();
console.log(image.id);
}


This return undefined. How can I get the image details?

Answer

if you have bind this in your constructor, you can try this <a href="#" onClick={(e) => { e.preventDefault(); this.handleImageClick(image); }} /> and update your handleImageClick parameter to handleImageClick(image){ .... } and removed event.preventDefault() inside.

Comments