Search code examples
javascriptreactjsonclickthislightbox

Retrieve the index of image on click ReactJS


I have a Gallery in my web application that I imported using 'React-Photo-Gallery.'

I am able to populate the gallery with images, and open up a photo carousel on click. How can I retrieve the index of the image clicked using the onClick method? activeIndex is set by default to 0, so upon clicking on any image, the first image in the array is displayed. I would like the clicked image to display in the carousel/Lightbox.

const mappingFunction = (img, index) => ({index, src: img.url, sizes: ["(min-width: 480px) 20vw,(min-width: 1024px) 25vw,25vw"], width: 4, height: 3});

const photosForGallery = images.map(mappingFunction)

After mapping the images, I display it like so:

<Gallery photos={photosForGallery} direction={"column"} columns={4} onClick={() => this.setState({ activeIndex: *use index here*, isOpen: true })} />

{isOpen && (
          <Lightbox
            mainSrc={urls[activeIndex]}
            mainSrcThumbnail={urls[activeIndex]}
            nextSrc={urls[(activeIndex + 1) % urls.length]}
            nextSrcThumbnail={urls[(activeIndex + 1) % urls.length]}
            prevSrc={urls[(activeIndex + urls.length - 1) % urls.length]}
            prevSrcThumbnail={urls[(activeIndex + urls.length - 1) % urls.length]}
            onCloseRequest={() => this.setState({ isOpen: false })}
            onMovePrevRequest={() =>
              this.setState({
                activeIndex: (activeIndex + urls.length - 1) % urls.length
              })
            }
            onMoveNextRequest={() =>
              this.setState({
                activeIndex: (activeIndex + 1) % urls.length
              })
            }
          />
        )}

Where I'm having difficulty is accessing the index of the selected image. I've tried using the 'this' keyword, and even tried implementing a callback function. However (correct me if I'm wrong), it seems like the selected element on click is the Gallery itself, rather than my image of choice. Any input would be appreciated, as I'm new to React / JS.

Will continue to update my question as I do more research, though any input is appreciated.


Solution

  • For component Gallery onClick function:

    Optional. Do something when the user clicks a photo. Receives arguments event and an object containing the index, Photos obj originally sent and the next and previous photos in the gallery if they exist

    http://neptunian.github.io/react-photo-gallery/api.html

    So all you may have to do is as below in order to get an index:

    <Gallery
      photos={photosForGallery}
      direction={"column"}
      columns={4}
      onClick={(e, { index }) => this.setState({ activeIndex: index, isOpen: true })} />  // <---- HERE