Sireini
Sireini

Reputation: 4262

ReactJS Pass key with an onClick function

I have an image gallery where I loop trough image objects and I want to pass the i to my onClick function. This is my image gallery code:

<div className="gallery clearfix">
  { block.gallery.map((item, i) => (
    i < 1 ?
     <div className="gallery-image" key={i} onClick={this.toggle}>
       <a href='' className="inner">
          <img src={item.images.thumbnail_sm} alt={block.title} srcSet={`${item.images.thumbnail_md} 1x, ${item.images.thumbnail_lg} 2x`} className="img-fluid image"/>
       </a>          
     </div>
     : null
     ))}
     <div className="gallery-thumbs">
       <div className="row">
        { block.gallery.map((item, i) => (
          i > 0 && i < (limit + 1) ?
          <div className="gallery-item" key={i} onClick={this.toggle}>
          <a href='' className="inner">
            <img src={item.images.thumbnail_sm} alt={block.title} srcSet={`${item.images.thumbnail_md} 1x, ${item.images.thumbnail_lg} 2x`} className="img-fluid image" title="" />
              { block.gallery.length > (limit + 1) && i == limit ?
                <div className="img-overlay">
                   <span className="img-indicator">{ block.gallery.length - (limit + 1) }+ <span className="hidden-xs">Foto's</span></span>
                </div>
             : null 
            }
          </a>
        </div>
        : null
        ))}
     </div>
   </div>
</div>

And this is my reactstrap modal where I want to show the image which is clicked:

<Modal isOpen={this.state.modal} toggle={this.toggle} className={this.props.className}>
      <ModalBody>            
        <img src={block.gallery[this.state.clickedImage].item.images.thumbnail_lg}/>
      </ModalBody>
    </Modal>

And here is the toggle function where I want to pass the clickedImage id:

toggle(id) {
    this.setState({
      clickedImage: id,
      modal: !this.state.modal
    });
  }

Upvotes: 1

Views: 13628

Answers (1)

Yichz
Yichz

Reputation: 9681

For best practice, I don't suggest binding within onClick, that cause it invoke bind every time when it's clicked. if you are using ES6, instead you should bind it in constructor:

Class MyComponent extends React.Component {
  constructor(props){
    super(props);
    this.toggle = this.toggle.bind(this);
  }
}

and

<div className="gallery-item" key={i} onClick={(i) => this.toggle(i)}></div>

UPDATE: like comments say. this is actually is not the best way, the best way is not to create new function and attach events with every render, which means it should be just

<div className="gallery-item" key={i} onClick={this.toggle}></div>

but since you need to pass the id, the best bet would be refactor it into smaller components like <GalleryItem> and pass the id by props

Worth to read: this

UPDATE: Also please look at comments, using dataset.index and data-index is even better

Upvotes: 2

Related Questions