StochasticNerd StochasticNerd - 1 month ago 11
React JSX Question

Handling the a onClick event in React

I'm using the following component to display a list of images in React.

class Viewer extends React.Component{

constructor(props){
super(props);
this.state = {
images : ImageList
};
}

render(){
return (
<div className="row">
<div className="image-viewer">
<ul className="list-inline">
{this.state.images.map(function (image) {
return (<li key={image.mediaId}><a href="#"><img src={image.src}
className="img-responsive img-rounded img-thumbnail"
alt={image.mediaId}/></a></li>);
})}

</ul>
</div>
</div>
);
}
}


I want to trap the
onClick
event on an image to do some processing, like apply a CSS to put an overlay. How do I do this in React. Please understand I'm rank new to React.

Answer

If you update your component to have onClick={this.onImageClick.bind(this, image.mediaId) you can then handle the onClick plus know which image it was that was clicked, save that on state, and use it to apply a className to the image on render (if that's what it is that you want!).

So something like this:

{this.state.images.map(function (image) {
  return (<li key={image.mediaId} className={this.state.activeImage === image.mediaId ? 'active' : undefined}><a href="#" onClick={this.onClick.bind(this, image.mediaId)}><img src={image.src}  className="img-responsive img-rounded img-thumbnail" alt={image.mediaId}/></a></li>);
})}

And then onClick handler -

onClick: function (mediaId) {
  this.setState({activeImage: mediaId});
}
Comments