skip to Main Content

I am trying to build an alternative to Google Photos, and I want to be able to display a Gallery, select files and display them.
I used react-grid-gallery which might be able to do both (image selection and display), but, I am able to select all images and display them, but not selecting particular ones.

My code:

"use client";

import "yet-another-react-lightbox/styles.css";

import { CustomImage, imagesData } from "./images";

import { Gallery } from "react-grid-gallery";
import Lightbox from "yet-another-react-lightbox";
import { useState } from "react";

export default function Page() {
    const [index, setIndex] = useState(-1);
    const [images, setImages] = useState(imagesData);
    const handleClick = (index: number, item: CustomImage) => setIndex(index);

    const hasSelected = images.some((image) => image.isSelected);
  
    const handleSelect = (index: number) => {
      const nextImages = images.map((image, i) =>
        i === index ? { ...image, isSelected: !image.isSelected } : image
      );
      setImages(nextImages);
    };
  
    const handleSelectAllClick = () => {
      const nextImages = images.map((image) => ({
        ...image,
        isSelected: !hasSelected,
      }));
      setImages(nextImages);
    };

    const slides = images.map(({ original, width, height }) => ({
        src: original,
        width,
        height,
    }));
  
    return (
      <div>
            <div className="p-t-1 p-b-1">
                <button onClick={handleSelectAllClick}>
                {hasSelected ? "Clear selection" : "Select all"}
                </button>
            </div>
            <Gallery
                images={images}
                onClick={handleClick}
                enableImageSelection={false}
                onSelect={handleSelect} 
            />
            <Lightbox
                slides={slides}
                open={index >= 0}
                index={index}
                close={() => setIndex(-1)}
            />
        </div>
    );
}

2

Answers


  1. Chosen as BEST ANSWER

    The issue was pretty trivial, it was just removing enableImageSelection={false} that fixed the issue.


  2. The problem is with the onClick atrribute at

    <Gallery
       images={images}
       onClick={handleClick}
       enableImageSelection={false}
       onSelect={handleSelect} 
    />
    

    This official example shows how to handle select single image.

    You should use onSelect instead of onClick.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search