diff --git a/package-lock.json b/package-lock.json index 0c401a1..a298a13 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@wethegit/react-gallery", - "version": "1.0.2", + "version": "2.0.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@wethegit/react-gallery", - "version": "1.0.2", + "version": "2.0.1", "license": "MIT", "dependencies": { "prop-types": "~15.8.1", diff --git a/package.json b/package.json index 3a6e737..b4fc68b 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@wethegit/react-gallery", - "version": "2.0.0", + "version": "2.0.1", "description": "A customizable, accessible gallery component for React projects.", "files": [ "dist" diff --git a/src/lib/components/gallery-context.jsx b/src/lib/components/gallery-context.jsx index 283b1b0..ad556fc 100644 --- a/src/lib/components/gallery-context.jsx +++ b/src/lib/components/gallery-context.jsx @@ -1,6 +1,6 @@ // packages import PropTypes from "prop-types" -import { createContext, useCallback, useRef, useState } from "react" +import { createContext, useCallback, useRef, useState, useEffect } from "react" // utils import classnames from "../utils/classnames" @@ -74,15 +74,27 @@ export const Gallery = ({ const goToIndex = useCallback( (index) => { + const validatedIndex = !items[index] ? 0 : index + setPreviouslyActiveIndex(activeIndex) - setActiveIndex(index) - const direction = index - activeIndex > 0 ? 1 : 0 - if (onChange) onChange({ oldIndex: activeIndex, newIndex: index, direction }) + setActiveIndex(validatedIndex) + const direction = validatedIndex - activeIndex > 0 ? 1 : 0 + if (onChange) + onChange({ oldIndex: activeIndex, newIndex: validatedIndex, direction }) }, - [activeIndex, onChange] + [activeIndex, onChange, items] ) + // This useEffect checks to see if the gallery item (index) exists, and if it + // doesn't it resets the gallery to the first slide (0). The edge case here + // becomes apparent when or if the length of gallery items changes, for instance + // separating/grouping items based on screen size. + + useEffect(() => { + if (!items[activeIndex]) goToIndex() + }, [activeIndex, items, goToIndex]) + const value = { galleryItems: items, itemNodes,