0

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.

  • 3
    Have you checked the docs? https://facebook.github.io/react/docs/handling-events.html – azium Oct 31 '16 at 23:39
  • Yes, that's where I've started from. But owing to my limited exposure to javascript I'm a bit at loss. –  Oct 31 '16 at 23:52
  • Possible duplicate of [React JS onClick event handler](http://stackoverflow.com/questions/28511207/react-js-onclick-event-handler) – Kitanga Nday Nov 01 '16 at 00:15
  • 1
    Try using `onClick` as in docs. Create a new function (preferably arrow) and in the element add `onClick={() => clickHandler()}` – Vincas Stonys Nov 01 '16 at 00:24

1 Answers1

0

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});
}
Rose Robertson
  • 1,236
  • 7
  • 14