Git Product home page Git Product logo

yifaneye / react-gallery-carousel Goto Github PK

View Code? Open in Web Editor NEW
212.0 4.0 29.0 2.26 MB

Carousel component ๐ŸŽ  supporting touch, mouse, keyboard, thumbnails, fullscreen, lazy loading, SSR and customisations. ๐Ÿ’ป Live editor: https://yifanai.com/rgcd1

Home Page: https://yifanai.com/rgc

License: MIT License

HTML 1.87% JavaScript 87.56% CSS 8.49% SCSS 2.08%
carousel gallery react javascript dependency-free css component accessibility thumbnails lightbox rtl mouse-emulation touch responsive swipe lazy-loading slide slider html reactjs

react-gallery-carousel's Introduction

react-gallery-carousel

npm version npm downloads npm bundle size prettier license Buy Me A Coffee

Mobile-friendly Carousel with batteries included (supporting touch, mouse emulation, lazy loading, thumbnails, fullscreen, RTL, keyboard navigation and customisations).

The first version was published on 31st March 2021.

Carousel controlled by finger

Try Live Demo

Background

What problems do other Carousels have?

I have used and carefully analyzed a lot of carousel/slider components. I summarized that their issues are:

  1. Some of them do not move the slide as the user swipes on the slide.
  2. Most of them do not support mouse dragging to move to the previous or the next slide. With the ones those support mouse emulation, some of them do not properly handle the case where the mouse leaves the carousel, which allow the user to continuously control the carousel.
  3. Most of them do not support keyboard navigation (i.e. left, right and tab key).
  4. Most of them cannot be maximized to fullscreen/modal/lightbox. With fullscreen, there is the issue of browser compatibility, i.e. iOS Safari on iPhone does not support the fullscreen API.
  5. Most of them do not have an easy solution for building thumbnails. With the ones those have thumbnails, most of the thumbnails cannot be freely scrolled which lead to poor user experience. In addition, most of the thumbnails cannot be lazy loaded.
  6. Most of them cannot lazy load (and preload) images. With the ones those can lazy load, most of them have transition that traverses the intermediate images when the user goes to a distant slide, which defeat the purpose of lazy loading.
  7. Some of them cannot autoplay. With the ones those can autoplay, they cannot auto pause. For example, when the user hits another tab or goes to another app, the autoplay on those carousels do not pause.
  8. Most of them do not respect the reduced motion settings by the user.
  9. Most of them disregard the velocity of the swipe and just set a constant transition duration.
  10. Some of their carousels will be in different sizes when the images/slides inside are in different sizes. Some of their transitions are bumpy when their images/slides are in different sizes.
  11. Most of them do not support custom elements in a slide.
  12. Most of them cannot be set to display in Right-to-Left (RTL).
  13. Some of them disable pinching to zoom, while some others glitch when pinching with 2 fingers. Besides, when the window is zoomed in, most of them still detect for touch swiping to move to the previous, or the next slide, while the intention of most users in this scenario is panning to see other parts of the current slide.
  14. Some of them will cause the slides to stuck its position on window resize or on mobile device orientation change, until another user interaction.
  15. Some of them can only have predetermined images (i.e. before the carousel component mounts).
  16. Most of them do not provide a solution for fallback/placeholder image (for when an image is not available).
  17. Some of them get zoomed in when the user double taps on the control, while the intention of most users in this scenario is to quickly go to the next after the next slide.
  18. Some of them remove the left or right button to indicate that there are no more slides in that direction. However, user is likely to click that spot where the button used to be, which causes undesired behaviours e.g. clicking on a link or button which is also at that spot.
  19. Some of them use the method of cloning the first, and the last slide to achieve looping (or infinite mode). I think that method is not great semantically.
  20. Some of them cannot distinguish a vertical swipe from a horizontal swipe, so that a not exactly vertical swipe moves the slides slightly horizontally; and a not exactly horizontal swipe moves the (document) page slightly vertically.

What did I set to achieve?

I wanted to write my own detail-oriented and exquisite carousel component that is easy to use yet solves/supports all these things above under the hood. ๐Ÿค“

I wanted to take my understanding of JavaScript events, DOM manipulation, browser APIs, cross-browser compatibility and performance debugging to the next level. ๐Ÿค“

I wanted to master React functional components, hooks, custom hooks and reconciliation. ๐Ÿค“

I wanted to learn more, place more care and attention to accessibility. I want to give focus outlines to the right users, support keyboard navigation, support screen reader, and follow W3C accessible carousel tutorials.

My carousel should support: touch, mouse emulation, keyboard navigation, modal (lightbox), thumbnails, autoplay (and auto pause), RTL (right to left for internationalization), image lazy loading (and preloading), responsive images, fallback image, reduced motion settings, instantaneous velocity detection, responsive design, images with any sizes, custom elements in a slide, pinch to zoom, customization and great accessibility. ๐Ÿ˜Ž

(e.g. To solve the last issue (#20) in the list above, my carousel should be able to detect a mostly vertical swipe and then fix the slides horizontally in the carousel. โœ… It should also be able to detect a mostly horizontal swipe and then fix the carousel vertically in the page. โœ…)

Demo

Live demo

Try Live Demo

Carousel controlled by finger

Carousel controlled by finger

Carousel controlled by cursor

Carousel controlled by cursor

Lighthouse report

Lighthouse Report on react-gallery-carousel Lighthouse Report with scores on react-gallery-carousel This lighthouse report is conducted on https://yifaneye.github.io/react-gallery-carousel/ in an incognito window on Chrome version 89.0.4389.114 (Official Build) (x86_64) on MacBook Pro with macOS version 10.15.7 (19H2) on 12th of April 2021.

Non-maximized carousels

Non-maximized Carousel

Maximized carousel

Maximized Carousel

Installation

npm install --save react-gallery-carousel

OR

yarn add react-gallery-carousel

Usage

import React from 'react';
import Carousel from 'react-gallery-carousel';
import 'react-gallery-carousel/dist/index.css';

const App = () => {
  const images = [9, 8, 7, 6, 5].map((number) => ({
    src: `https://placedog.net/${number}00/${number}00?id=${number}`
  }));

  return (
    <Carousel images={images} style={{ height: 500, width: 800 }} />
  );
};

export default App;

Props

To customize the carousel, use the following props:

Name Type Default Description
images Array undefined Array of image(s) to be placed in the carousel. Each image object (e.g. example object) in the array has a required attribute 'src'.
children node or Array of nodes undefined HTML element(s) to be placed into the carousel for user-managed slides. It (they) will be placed only if the 'images' prop is falsy.
thumbnails Array of nodes undefined HTML element(s) to be placed into the thumbnail view at the bottom. If not provided, the slides will be used. If provided, it must have the same length as the slides.
index Number undefined Initial (0-indexed) index of the slides of the carousel as a whole number starting from 0.
isRTL Boolean false If true, the slides of the carousel starts from the right (and also auto plays from the right to the left).
isLoop Boolean true If true, the carousel form a loop (i.e. going left from the left-most slide lands at the right-most slide, and vice versa) from the ribbon of slides.
isMaximized Boolean false If true, the carousel is maximized initially.
shouldLazyLoad Boolean true If true, images that are not yet in the viewport of the carousel will be lazy loaded, except the 2 adjacent images from either side of the carousel which will be preloaded.
canAutoPlay Boolean true If true, the carousel has auto play capability.
isAutoPlaying Boolean false If true, the carousel auto plays initially.
autoPlayInterval Number 5000 Interval of the auto play (in milliseconds).
hasTransition Boolean true If false, the carousel does not have transition in moving between slides.
swipeThreshold Number 0.1 Threshold swipe distance (in percentage of the width of the viewport of the carousel) to move to the previous or the next slide.
swipeRollbackSpeed Number 0.1 Speed of the transition (in pixels per millisecond) in moving back to the current slide after a swipe smaller than swipeThreshold.
transitionSpeed Number 1 Speed of the transition (in pixels per millisecond) in moving to the previous or the next slide on non-swipe updates on the carousel.
transitionDurationLimit Number 750 Limit of transition duration (in milliseconds). The limit is used to flatten transition duration, where the maximum transition duration infinitely approaches this value.
transitionDurationMin Number 250 Minimum transition duration (in milliseconds). Transition duration can be set to be a constant with transitionDurationMin === transitionDurationMax.
transitionDurationMax Number undefined Maximum transition duration (in milliseconds). It will have precedence over transitionDurationMin, if transitionDurationMin > transitionDurationMax.
widgetsHasShadow Boolean false If true, the following widgets (with *) have shadows. (Note: if true, the transition will tend to drop frames when there are a large number of slides.)
hasLeftButton * Boolean or String 'centerLeft' If false, the carousel does not show left button. Its position can be specified by one of small widget positions.
hasRightButton * Boolean or String 'centerRight' If false, the carousel does not show right button. Its position can be specified by one of small widget positions.
hasMediaButton * Boolean or String 'topLeft' If false, the carousel does not show media button (i.e. play/pause button). Its position can be specified by one of small widget positions. If the value of 'canAutoPlay' is falsy, media button will not be shown on the carousel.
hasSizeButton * Boolean or String 'topRight' If false, the carousel does not show size button (i.e. maximize/minimize button). Its position can be specified by one of small widget positions.
hasIndexBoard * Boolean or String 'topCenter' If false, the carousel does not show index board (i.e. currentIndex / totalNumberOfSlides). Its position can be specified by one of small widget positions.
hasDotButtons * Boolean or String false If false, the carousel does not show dot buttons (i.e. array of dots indicating the current slide in relation to other slides). Its position can be specified by one of large widget positions.
hasCaptions * Boolean or String false If false, the carousel does not show caption for each image. Its position can be specified by one of large widget positions.
hasThumbnails Boolean true If false, the carousel does not show thumbnails at the bottom.
hasLeftButtonAtMax * Boolean or String undefined If false, the maximized carousel does not show left button. Its position can be specified by one of small widget positions. It overrides 'hasLeftButton' prop for the maximized carousel. If not specified, the value of 'hasLeftButton' will be used.
hasRightButtonAtMax * Boolean or String undefined If false, the maximized carousel does not show right button. Its position can be specified by one of small widget positions. It overrides 'hasRightButton' prop for the maximized carousel. If not specified, the value of 'hasRightButton' will be used.
hasMediaButtonAtMax * Boolean or String undefined If false, the maximized carousel does not show media button (i.e. play/pause button). Its position can be specified by one of small widget positions. It overrides 'hasMediaButton' prop for the maximized carousel. If not specified, the value of 'hasMediaButton' will be used. If the value of 'canAutoPlay' is falsy, media button will not be shown on the maximized carousel.
hasSizeButtonAtMax * Boolean or String undefined If false, the maximized carousel does not show size button (i.e. maximize/minimize button). Its position can be specified by one of small widget positions. It overrides 'hasSizeButton' prop for the maximized carousel. If not specified, the value of 'hasSizeButton' will be used.
hasIndexBoardAtMax * Boolean or String undefined If false, the maximized carousel does not show index board (i.e. currentIndex / totalNumberOfSlides). Its position can be specified by one of small widget positions. It overrides 'hasIndexBoard' prop for the maximized carousel. If not specified, the value of 'hasIndexBoard' will be used.
hasDotButtonsAtMax * Boolean or String undefined If false, the maximized carousel does not show dot buttons (i.e. array of dots indicating the current slide in relation to other slides). Its position can be specified by one of large widget positions. It overrides 'hasDotButtons' prop for the maximized carousel. If not specified, the value of 'hasDotButtons' will be used.
hasCaptionsAtMax * Boolean or String undefined If false, the maximized carousel does not show caption for each image. Its position can be specified by one of large widget positions. It overrides 'hasCaptions' prop for the maximized carousel. If not specified, the value of 'hasCaptions' will be used.
hasThumbnailsAtMax Boolean undefined If false, the maximized carousel does not show thumbnails at the bottom. It overrides 'hasThumbnails' for the maximized carousel. If not specified, the value of 'hasThumbnails' will be used.
leftIcon node undefined Left icon (HTML element) to be placed into the left ArrowButton.
rightIcon node undefined Right icon (HTML element) to be placed into the right ArrowButton.
playIcon node undefined Play icon (HTML element) to be placed into the MediaButton.
pauseIcon node undefined Pause icon (HTML element) to be placed into the MediaButton.
minIcon node undefined Minimize icon (HTML element) to be placed into the SizeButton.
maxIcon node undefined Maximize icon (HTML element) to be placed into the SizeButton.
activeIcon node undefined Active dot icon (HTML element) to be placed into the active DotButton indicating the current slide.
passiveIcon node undefined Passive dot icon (HTML element) to be placed into the passive DotButton indicating all non-current slide(s).
elements node undefined Custom elements (HTML element) to be placed into the Carousel.
shouldSwipeOnMouse Boolean true If true, the carousel can be swiped by the cursor using a mouse or a track pad.
shouldMaximizeOnClick Boolean false If true, the carousel can be maximized by clicking.
shouldMinimizeOnClick Boolean false If true, the carousel can be minimized by clicking.
shouldMinimizeOnSwipeDown Boolean true If true, the carousel can be minimized by touch swiping down.
onIndexChange Function ({curIndex, curIndexForDisplay}) => {} Callback function invoked when the current index of the slides of the carousel is being updated. (Note: it is called regardless of whether index value's before and after are the same. curIndex is 0-indexed whilst curIndexForDisplay is 1-indexed)
onSwipeMoveX Function (displacementX) => {} Callback function invoked when the carousel is being swiped in a horizontal swipe. (Note: available from v0.2.0)
onSwipeMoveY Function (displacementX, displacementY) => {} Callback function invoked when the carousel is being swiped in a vertical swipe. (Note: available from v0.2.0)
onSwipeEndDown Function () => {} Callback function invoked when the carousel is being swiped in a downward swipe. (Note: available from v0.2.0)
onTap Function () => {} Callback function invoked when the carousel is being tapped (i.e. from mousedown to mouseup without mousemove, or from touchstart to touchend without touchmove. (Note: available from v0.2.0)
objectFit String 'cover' CSS 'object-fit' style to be placed on each image, on the non-maximized carousel.
objectFitAtMax String 'contain' CSS 'object-fit' style to be placed on each image, on the maximized carousel.
zIndexAtMax Number undefined CSS 'z-index' attribute to be placed on the maximized carousel.
thumbnailWidth String '10%' Width of each thumbnail. e.g. '20%', '20vw', '200px', 'auto'.
thumbnailHeight String '10%' Height of each thumbnail (as well as the height of thumbnails). e.g. '20%', '20vh', '200px', 'auto'.
className String undefined Class name(s) to be placed on the non-maximized carousel.
style Object undefined Inline style(s) to be placed on the non-maximized carousel.

Handlers

To customize the carousel in a declarative manner, use the props above (e.g. isAutoPlaying, isMaximized, index).

To customize the carousel in an imperative manner, use the following handlers (on the forwarded ref):

Name Description
play() Start the autoplay by setting the isPlaying state to true. (Note: need >= v0.2.0)
pause() Pause the autoplay by setting the isPlaying state to false. (Note: need >= v0.2.0)
toggleIsPlaying() Toggle the isPlaying state. (Note: need >= v0.2.0)
maximize() Maximize the carousel by setting the isMaximized state to true. (Note: need >= v0.2.0)
minimize() Minimize the carousel by setting the isMaximized state to false. (Note: need >= v0.2.0)
toggleIsMaximized() Toggle the isMaximized state. (Note: need >= v0.2.0)
goLeft() Go to the left slide. (Note: need >= v0.2.0)
goRight() Go to the right slide. (Note: need >= v0.2.0)
goToIndex(index) Go to the specified index. (Note: need >= v0.2.0)

Definitions

  • Developer users: developers who use this component.
  • Users: end users of the products which use this component.

Image Object Example

{
  src: `https://placedog.net/700/420?id=1`, // required
  srcset: `https://placedog.net/400/240?id=1 400w, https://placedog.net/700/420?id=1 700w, https://placedog.net/1000/600?id=1 1000w`,
  sizes: '(max-width: 1000px) 400px, (max-width: 2000px) 700px, 1000px',
  alt: `Dogs are domesticated mammals, not natural wild animals. They were originally bred from wolves. They have been bred by humans for a long time, and were the first animals ever to be domesticated.`,
  thumbnail: `https://placedog.net/100/60?id=1`
}

Widgets Settings

[
  'hasLeftButton',
  'hasRightButton',
  'hasMediaButton',
  'hasSizeButton',
  'hasDotButtons',
  'hasIndexBoard'
],

Small Widget Positions

[
  'topLeft', 'topCenter', 'topRight',
  'centerLeft', 'centerCenter', 'centerRight',
  'bottomLeft', 'bottomCenter','bottomRight'
]

Large Widget Positions

['top', 'bottom']

FAQ

Q: How to place video, text or any element into a slide?

A: Custom elements in slides (called user-managed slides) can be placed using the children prop. Example: demo, code. Note: it (they) will be placed only if the 'images' prop is falsy.

Q: Why the element and font in my carousel is different from the one on the demo?

A: There are some browser default styles. Set a font, some global styles and/or use normalize.css will help. Example: code.

Q: Can I remove hash from generated file names? How to do it?

A: Yes. In node_modules/microbundle-crl/dist/microbundle.js, Change useHash: true to useHash: false.

Q: Are there TypeScript type definitions for this package?

A: Yes. @types/react-gallery-carousel package contains type definitions for react-gallery-carousel through DefinitelyTyped.

Roadmap

  • Support for dynamic images (since v0.1.1)
  • Support handlers and listeners (since v0.2.0)
  • Add TypeScript type Definitions (since v0.2.0)
  • Support for server-side rendering (since v0.2.3)
  • Momentum-based mouse dragging on thumbnails (since v0.2.4)
  • Allow customization using custom elements (since v0.4.0)
  • Use TypeScript
  • Implement more unit tests and E2E tests
  • GitHub Actions

Contributing

Issues and pull requests are welcomed.

(Note: please use Prettier for code formatting.)

Local Development for Contributing

  1. In a terminal tab, run rollup to watch the src/ directory and to automatically compile the local version of react-gallery-carousel into the dist/ directory. (Note: the compilation does not minify the package for readability. The decision on minification is left to the developer users).
yarn install
yarn start
  1. In another terminal tab, run create-react-app dev server to serve the example in the example/ directory, which is dependent on the local version of react-gallery-carousel.
cd example
yarn start

(Note: it is not helpful to run either of these commands in the background, because you will miss out on errors and warnings.)

License

MIT ยฉ Yifan Ai

react-gallery-carousel's People

Contributors

a-tonchev avatar cyklan avatar yifaneye avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

react-gallery-carousel's Issues

Images are not loading when pulling them in from firebase firestore

Hi there, this probably isnt a problem with the repo, more me not understanding how to do this properly.

Here is where I pull in the product from firebase:

useEffect(() => {
        if (listingID === '') {
            window.alert("no id")
        } else {
            var docRef = db.collection("listings").doc(listingID);
            docRef.get().then((doc) => {
                if (doc.exists) {
                    setListing(doc.data());
                } else {
                    console.log("No such document!");
                }
            }).catch((error) => {
                console.log("Error getting document:", error);
            });
        }
    }, [])

And then I assign the photos from the product data to "images" and follow the object pattern that the carousel requires:

const [images, setImages] = useState([]);
useEffect(() => {
        if (listing.listingPhotos != null) {
            console.log("SETTING IMAGES");
            listing.listingPhotos.forEach(element => {
                var imageURL = {
                    src: element
                }
                setImages(images => [...images, imageURL]);
            });
        }
    }, [listing])

And then in my jsx:

return (
        <div className="listingPage">
            <div className="listingPage__main">
                <div className="listingPage__left"></div>
                <div className="listingPage__center">
                    <div className="listingPage__center__itemContainer">
                        <div class="listingPage__center__itemContainer__gridSection image">
                            <Carousel images={images} />
                        </div>
...

When the page loads, I can see that the images are in the carousel object, however it doesnt render them, so I'm guessing its rendering the carousel before it has the images ready? Im new to react so can anyone give me some guidance how to make it wait until the images are ready? Thanks!
image

shouldMaximizeOnClick doesn't work

I have Carousel with shouldMinimizeOnClick and shouldMaximizeOnClick. In mobile version maximize working great, but if I click on toggle device toolbar and click on image it doesn't work.

Steps to reproduce the behavior:

  1. Go to https://yifaneye.github.io/react-gallery-carousel/
  2. Open console and click on "Toggle device toolbar". Choose Some phone(for example IPhone XR)
  3. Scroll down to carousel with shouldMaximizeOnClick
  4. See error

image
image

Swipe on mouse wheel?

It would be cool if we could swipe the carousel with the mouse wheel.

Great library.

Thank you!

Typescript support

Hi,
first of all thanks for this amazing library.
are you planning to add types?

I'm using react with typescript.
For anyone in same situation, just put //@ts-ignore above the import.

Pause on Hover

Is your feature request related to a problem? Please describe.
I am having trouble finding a good way to get the transitions to pause during a hover event on the carousel

Describe the solution you'd like
A boolean prop that allows us to 'pauseOnHover'

Describe alternatives you've considered
Tried using useEffect but I can't attach this to any hover event on the carousel

Additional context
Add any other context or screenshots about the feature request here.

No Caption if use {children}

I use the react-gallery-carousel for different types of media, so I add media items as children. But even for <img ...> with alt attribute set those captions (alt text) doesn't show up. It works only when I use images attribute in .

Expect: the way to add caption for each {children} items.

Carousel Button Titles

Is your feature request related to a problem? Please describe.
When hovering over the circular button, I have the title "Go" or "Stay".

Describe the solution you'd like
I would like to be able to change/translate these titles.

Describe alternatives you've considered
Or just be able to get them out of there.

Additional context
image

The last slide is not displayed from the second loop when there are exactly 2 slides

Describe the bug
The last slide is not displayed from the second loop in carousel with loop when there are exactly 2 slides.

To Reproduce
Steps to reproduce the behavior:

  1. Make a carousel with loop and with 2 slides
  2. Click on the right arrow button to loop all slides once
  3. Click on the right arrow button to go to the last slide
  4. See the error that the last slide is not displayed

Expected behavior
The last image should be display at the last index.

Screenshots
The GIF below is taken from the initial loading to the occurrence of the bug.
second_image_issue

Desktop (please complete the following information):

  • macOS
  • Chrome
  • Version 89.0.4389.90 (Official Build) (x86_64)

Swipe on a slide does not freeze autoplay countdown

Describe the bug
Swipe on a slide (manual intervention) does not freeze autoplay countdown.

To Reproduce
Steps to reproduce the behavior:

  1. Go to a carousel with autoplay capability
  2. Click on the media button to start the autoplay, if the autoplay is not set to start automatically
  3. Swipe a slide and do not release the slide
  4. See error that the carousel advances to the next slide when the touch/mouse dragging has not finished

Expected behavior
The carousel should not advance to the next slide when the touch/mouse dragging has not finished

Screenshots
Apr-29-2021 23-21-15

Desktop (please complete the following information):

  • macOS
  • Chrome
  • Version 89.0.4389.90 (Official Build) (x86_64)

Type issue on goToIndex

Describe the bug
When using the package with typescript and react there is an issue on the type of goToIndex. It's type does not support any parameters, when it should support (index:number)

To Reproduce
Steps to reproduce the behavior:

  1. Install react-gallery-carousel and @types/react-gallery-carousel
  2. Click on try to use ref.current.goToIndex(1)
  3. See error (Expected 0 arguments, but got 1.) on the "1" paramenter of goToIndex

Expected behavior
No type error when using the index parameter on goToIndex;
If I'm not wrong, the CarouselRef type should be:

    type CarouselRef<T = unknown> = T & {
        ...
        goToIndex(index: number): void;
    };

Support for video files

This is the best carousel library. but i would like to request a feature to support video files.

The component can't be used in a TS React project

Describe the bug
The component can't be imported into vanilla TS React project

To Reproduce
Follow the steps provided in the project's README, namely:

  1. npm install --save react-gallery-carousel
  2. import Carousel from 'react-gallery-carousel';
    Error: TS7016: Could not find a declaration file for module 'react-gallery-carousel'. '/Users/denis/project/my/z-nails/z-nails-web/node_modules/react-gallery-carousel/dist/index.js' implicitly has an 'any' type.
    Try npm i --save-dev @types/react-gallery-carousel if it exists or add a new declaration (.d.ts) file containing declare module 'react-gallery-carousel';

Cant make this module work

Hi,
the live example looks really nice but

  • the example in clone from repo doesn't work with npm start
  • it doesn't render correctly when I install the library into my own project.

I don't know whats wrong but its pity that such nice looking library can not be implemented smoothly.

Invalid or unexpected token

Describe the bug
A clear and concise description of what the bug is.
SyntaxError: Invalid or unexpected token
at wrapSafe (internal/modules/cjs/loader.js:1053:16)
at Module._compile (internal/modules/cjs/loader.js:1101:27)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1157:10)
at Module.load (internal/modules/cjs/loader.js:985:32)
at Function.Module._load (internal/modules/cjs/loader.js:878:14)
at Module.require (internal/modules/cjs/loader.js:1025:19)
at require (internal/modules/cjs/helpers.js:72:18)
at Object. (C:\Users\Josh\Documents\pcswaps\swap-react\node_modules\react-gallery-carousel\dist\index.js:5:40)
at Module._compile (internal/modules/cjs/loader.js:1137:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1157:10)
C:\Users\Josh\Documents\pcswaps\swap-react\node_modules\react-gallery-carousel\dist\placeholder.jpg:1
๏ฟฝPNG

To Reproduce
Steps to reproduce the behavior:

  1. Go to '...'
  2. Click on '....'
  3. Scroll down to '....'
  4. See error

I'm using Next.js in a monorepo with lerna but other than that I'm not exactly sure what's causing this issue. It looks like it might be trying to find placeholder.jpg(1) but I don't see why. I also cloned the repo and ran the next example and it seemed to work fine. I also tried not hoisting the this module and that didn't help. Kind of at a loss but I'm very excited to make use of this package. Been searching for some time for a good gallery that is performant rather than writing my own and it seems like you've done that.

Expected behavior
A clear and concise description of what you expected to happen.

Screenshots
If applicable, add screenshots to help explain your problem.

image
image

Desktop (please complete the following information):

  • OS: [e.g. iOS] Windows 10
  • Browser [e.g. chrome, safari] chrome
  • Version [e.g. 22]

Smartphone (please complete the following information):

  • Device: [e.g. iPhone6]
  • OS: [e.g. iOS8.1]
  • Browser [e.g. stock browser, safari]
  • Version [e.g. 22]

Additional context
Add any other context about the problem here.

Caption for image always has vertical and horizontal scrolls even they are not required

To Reproduce
Use react-gallery-carousel with "images" and "hasCaptions" attributes. All caption elements have vertical and horizontal scrollbars even if the caption element doesn't require them.

Expected behavior
No scrollbars if they are not required.

To Fix
Replace "overflow: scroll" to "overflow: auto" caption's css style letting browser to handle scrollbars appearance.

Pictures don't appear properly when sliding

Hello yifaneye!

First, thank you for this very useful carousel! However, I am experiencing a little problem with the image display.

The issue
The first image seems to appear correctly. But as soon as I slide to the next ones, everything seems to shift slowly to the right. As a result, I have two photos appearing on one slide.

Expected behavior
How do I make one photo appear properly per slide?

Specifications

  • My photos are all different sizes.
  • They are fetched from a database that I created.
  • I wrapped the carousel in a wrapper to position it in the center of my page.
  • Browser: Chrome
  • I'm new to coding! I've read the documentation and tried to find information on StackOverflow and ChatGPT but haven't found anything ๐Ÿ˜…

Screenshots
I made a loom record of the carrousel

<>
      <div className="pageContainer">
        <div className="titleWrapper">
          <h1>
            {villa.Villa.name} โ€” {villa.Villa.region}
          </h1>
          <div>
            <Link to={-1}>Back</Link>
          </div>
        </div>

        <div className="flexRow">
          <Carousel
            images={images}
            style={{ height: 500, width: 600 }}
            hasMediaButton={false}
            shouldLazyLoad={true}
            objectFit="contain"
          ></Carousel>
        </div>
      </div>
    </>
  );
}
.titleWrapper {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  padding-bottom: 4vh;
  margin-left: 4.5vw;
  margin-right: 4.5vw;
  align-items: flex-end;
}

.titleWrapper > h1 {
  margin: 0;
  padding: 0;
}

I hope this helps. I'm looking forward to your response. Thank you in advance!

dotButtons has an index undefined when loading dynamic images

Describe the bug
I load images from my back-end dynamicaly in the carousel. I want to display the dotButtons but at the firsts renders, the console is printing "Warning Failed prop type: The prop curIndex is marked as required in DotButtons, but its value is undefined."

To Reproduce
Steps to reproduce the behavior:

  1. Load images asynchronously
  2. Turn on the dotButtons display in the carousel
  3. See the error in the console

Expected behavior
It doesn't crash the app and it keep the expected behavior when I navigate in the carousel (the active dot is correct, the unactives ones aswell and the total is good). But it still print a problem in the console.

Desktop :

  • OS: Windows 10
  • Browser: Mozilla Firefox
  • Version 87.0

Need caption for {children} elements

I use react-gallery-carousel with {chidren} to show different types of items in carousel (images, video and audio media).
It works fine but I cannot add the caption for the item.

Solution I'd like
Add special component that has required attributes like caption and supports {children} to handle user defined inner html as usual React component.

Slides that have an a-tag inside them aren't clickable on mobile

Describe the bug
Let's say I have two slides and both slides have an <a> tag around them. When viewing them on a phone (or the mobile view in a browser) and clicking on them, i won't navigate

To Reproduce

  1. Create a new Gallery that doesn't maximize on click
  2. wrap every slide with an a tag
  3. view on a mobile device (or mobile view in a browser)
  4. click the slide
  5. You won't navigate

Expected behavior
I expect that a tags (and probably buttons, haven't tested those) still work normal when viewing them on mobile

Smartphone (please complete the following information):

  • Device: any
  • OS: any
  • Browser: any

Transitions aren't working

I'm not able to see the slide transitions as shown in the demo videos, even on the demo site. I didn't dig into your code and/or css yet, but thought I'd report what I'm seeing in case you know off-hand what might be causing it.

I've created a sandbox here to show how I've attempted to adjust the props to enable transition effects:
https://codesandbox.io/s/recursing-agnesi-7s6n1z?file=/src/App.js

Tested on Chrome, FF, Edge

Kind Regards,
Jonathan

Maximize and minimize using soft touch on trackpad

Describe the bug
If I use the soft touch of my Macbook trackpad and do not push it down physically in order to click the image to zoom in or out (maximizeOnClick and minimizeOnClick), it sometimes works and sometimes doesn't. This happens because the event.buttons property of the mouseDown-Event is randomly set to 0 or 1. As you check for it to be > 0, it randomly just does nothing.

It would be cool if you could remove the check for event.buttons > 0 from the handleMouseDown method for it to work on Macbooks again.

To Reproduce
Steps to reproduce the behavior:

  1. activate shouldMaximizeOnClick and/or shouldMinimizeOnClick
  2. Tap on the image using soft touch of trackpad multiple times
  3. randomly it will do what you expect it to do or just do nothing without an error

Expected behavior
maximize and minimize work with trackpad

Desktop (please complete the following information):

  • OS: iOS 12.6
  • Browser Chrome
  • Version 108.0.5359.94

Left and right keys does not work when a widget is focused

Describe the bug
Left and right keys on the keyboard do not work when a widget is focused

To Reproduce
Steps to reproduce the behavior:

  1. Go to a carousel with more than 1 slide
  2. Focus a widget using the Tab key
  3. Press the left key
  4. See error

Expected behavior
Left and right keys should work when a widget is focused

Screenshots
Apr-27-2021 23-52-07

Desktop (please complete the following information):

  • macOS
  • Chrome
  • Version 89.0.4389.90 (Official Build) (x86_64)

Allow thumbnails to be at the side

Is your feature request related to a problem? Please describe.
I'm trying to move the thumbnails from the bottom to the right, like the image below which I did by modifying the CSS, but the problem is that mouse events (useMouse/useMouseDrag ?) only work on the X direction.

Describe the solution you'd like
Allow a new prop (orientation?) to be passed to mouse event handers (possibly separate for thumbnails and images).

Describe alternatives you've considered
None, not sure what I could try.

Additional context

What I want to do:
image

CSS, roughly:

<thumbnail> ul {
  display: flex;
  flex-direction: column;
}

<thumbnail> ul li {
  min-width: 100%;
  min-height: 10%;
}

shouldSwipeOnMouse block onTap handler

When you add prop shouldSwipeOnMouse you cannot maximize slide

To Reproduce
Steps to reproduce the behavior:

  1. Add shouldSwipeOnMouse to gallery
  2. Click on image
  3. See error

Expected behavior
Maximize image

Additional context
I already fixed it by adding
image
image
but I don't know how to test it

Add classNameAtMax and stylesAtMax

Since we have className and styles for non-maximized view, it should be nice to have also such ones for maximized view.

I love the way material ui is doing this with the classes object:

https://material-ui.com/customization/components/

I think best would be something like

<Carousel
  classnames={{
    thumbnail: classNameOfThumbnail,
    activeThumbnail: classNameOfActiveThumbnail,
    maximizedCarousel: classNameOfMaximizedCarousel,
    image: classNameOfImage,
    imageContainer: classNameOfImageContainer,
    ...etc
  }}
>

TypeError: Cannot read property 'style' of null

Describe the bug
The error line:

() => (slidesRef.current.style.transitionDuration = null),

To Reproduce
Steps to reproduce the behavior:

  1. Click on the page using the carousel
  2. Click the browser back button to go back
  3. Click forward to go back, the error will occur

Screenshots
https://gyazo.com/137e2ae73497db26a678f0dd0fffab61

Desktop (please complete the following information):

  • OS: Windwos
  • Browser Microsoft Edge

ๅคš่ฐข๏ผ

Issues lazy loading images in gallery

Describe the bug
A clear and concise description of what the bug is.

Sometimes lazy loaded images don't load. From what I can see it doesn't get switched to a real url when swiping or clicking the url so when the image is actually on screen this causes the gallery to try to load the image from https://{path}/[object%20Object]

To Reproduce
Steps to reproduce the behavior:

  1. Go to '...'
  2. Click on '....'
  3. Scroll down to '....'
  4. See error
    Not exactly sure how to reproduce consistently, but here is an example

Website has been updated to that issue is no longer present
This is our staging server. The login is dev/dev so you can see the behavior. I tried to do some debugging but couldn't find exactly what was causing the issue. The urls are definitely valid. This doesn't happen if lazy loading is disabled

Expected behavior
A clear and concise description of what you expected to happen.
Should lazy load the image

Screenshots
If applicable, add screenshots to help explain your problem.
image

Desktop (please complete the following information):

  • OS: [e.g. iOS] windows 10
  • Browser [e.g. chrome, safari] chrome
  • Version [e.g. 22]

Smartphone (please complete the following information):

  • Device: [e.g. iPhone6] iphone xr
  • OS: [e.g. iOS8.1] latest
  • Browser [e.g. stock browser, safari] safari
  • Version [e.g. 22]

Additional context
Add any other context about the problem here.

This does happen on my iphone as well. See specs above.

Typo: minIcon Typescript type is not accepted by Carousel Component

Describe the bug
minIcon is the actual prop that Carousel component accepts as per the api(https://github.com/yifaneye/react-gallery-carousel#props) but @types/react-gallery-carousel has typo miniIcon

Please check the screenshots below

Issue:
I am using this in a nextjs project everything works but nextjs is not building the project because of the type error.

**Screens
Screenshot 2022-02-06 at 4 29 28 PM

Check last but one prop in the above image

next js build issue due to the typo.
Screenshot 2022-02-06 at 4 27 10 PM

Custom childrens for the thumbnails

When we use "images" parameter, the thumbnails works great, but when we use children instead, thumbnail is exact the same like the main item.

It would be awesome to add thumbnailsChildren, where we can place separate thumbnails into the gallery.

e.g.

<Carousel
thumbnails={thumbnails.map(thumbnail => )}

{images.map(image => <MyImage src={image.src} {...image.renderSomething} />)}

Expose a prop to allow a custom placeholder image

Is your feature request related to a problem? Please describe.
Hello! Sorry to bother you again, but I would like to be able to display a custom image when the provided src url in the images array turns out to be a broken link. Right now it looks like the carousel deals with this case, but the placeholder image must be the one in the library. Since I can't provide image components directly (unless I use children which in this case, I would prefer not to), I have to defer to the carousel's custom error handling in case the url is not found, but I would like my fallback to be a bit more descriptive than the black rectangle currently provided as the library's fallback.

Describe the solution you'd like
It would be nice if there was a prop provided so that I can use a custom placeholder image.

Describe alternatives you've considered
I've looked into whether I can customize the placeholder image without requesting this feature, but ironically, because this library provides a fallback image, I can't simply add a css rule that only kicks in for broken images, and the lack of direct control over images unless I use the children prop severely limits any other options.

Additional context
Thank you!

Handlers and Listeners

One other demanded feature would be to have handlers outside of the Component, and also listeners before and after action.

E.g.

Handlers:
you could provide an ref to the HOC, and just call from outside this.galleryRef.setActiveSlide(3) or this.galleryRef.setFullScreen()

Listeners:
beforeSwipe, afterSwipe, beforeScreen

I think that are the only things that I am missing from other galleries. Else I really like your gallery! :)

Allow zoom in in mobile double tab

Right now if I double tap image in full screen mode it has zoom in effect, but it zooms also arrows and the whole window. After exiting zoom I can not slide any more until I click again on the arrow, after that everything starts to work normal.

It would be nice to have double-tap and 2 finger stretch zoom similar like amazon when open on mobile view:

https://www.amazon.de/gp/aw/d/B01C37CRZS/?_encoding=UTF8&pd_rd_plhdr=t&aaxitk=d0cbebe4194d6edc5093cd9cda6b705d&hsa_cr_id=5069197050902&ref_=sbx_be_s_sparkle_scm_asin_0_img&pd_rd_w=SpWBU&pf_rd_p=93aef975-2fed-4353-91a2-d32b278d7c02&pd_rd_wg=rBmS8&pf_rd_r=5RZJMMX3CJ35EZN88GSC&pd_rd_r=2787af93-7ff4-4207-9d1a-187bd98b598f#immersive-view_1624784083156

How to use array of photos in carousel user managed slide ?

Hi yifaneye,

I am trying to make , user managed slide from an object which is having different kind of values and Photos[] array is one of among them but I am unable to use my Photos[] properly , when I used it with the map function of array it is showing photos but it is overlapping them on other slides too . Can you please tell me how can I do this properly so that each photo comes on different slide ?

Thanks,

Only show the first image

Describe the bug
Only the first image is rendered, if I select another image it will just show a black background, thumbnails are rendered below correctly but when selecting any image other than the first it shows as black background

To Reproduce
Steps to reproduce the behavior:
1- run the example code in the "Usage" section of the readme
2- select a slide other than the first one, you will see a black screen

Expected behavior
All slides should render correctly

Screenshots
Screenshot 2023-05-11 at 1 56 51 PM

Desktop (please complete the following information):

  • OS: Macos
  • Browser :Firefox
  • Version 113

Smartphone (please complete the following information):
Not tested

Additional context
N/A

Add option for scroll bar for thumbnails

Is your feature request related to a problem? Please describe.
I'm using the carousel in a context where there are likely to be hundreds of thumbnails. In this case the user will likely want to use the thumbnails to navigate to the right slide, but the user is likely to only have access to a vertical scroll wheel on a mouse, making looking through all the thumbnails difficult.

Describe the solution you'd like
It would be nice if there could be a prop enabling a scrollbar to show up allowing the user to scroll through the thumbnails.

Describe alternatives you've considered
I tried overriding the css in the component to add a scrollbar to the thumbnails container, but because I wasn't accessing the container directly, the effect ended up being that I stole vertical space from the thumbnails, making them so small that they were unusable for navigation, defeating the purpose. If this feature were native, then an option to enable the scrollbar could perhaps instead borrow the needed space from the image panel, where those pixels are less likely to make such a dramatic difference. I also looked into whether there is a way to convert vertical scroll wheel inputs into horizontal scrolling, but the hacks I found didn't seem to work without direct access to the component.

Additional context
Thank you :)

Image displayed is not matching with the index parameter

Describe the bug
I'm giving to the carousel the index parameter since I want to totally control the carousel. The bug is if I slide the carousel but for some external reason in my program I dont want the index to change, the image will still change but the arrows and dot buttons will still be corrects and remains at the right index.

To Reproduce
Steps to reproduce the behavior:

  1. Declare a variable to store the index and give it to the carousel
  2. Do not update this variable in the callback onIndexChange
  3. See error : the image is still changing while the arrows and buttons are not following the same behavior and remains at the index passed in the component.

Expected behavior
Since the props index is passed, the displayed image should follow the index and shouldn't have it's own behavior.

Desktop:

  • OS: Windows 10
  • Browser: Opera GX

Npm install doesnt work currently

Describe the bug
There is upstream conflict with react

To Reproduce
$npm install

Solution
Update package.json as such;

  "devDependencies": {
    "babel-eslint": "^10.0.3",
    "cross-env": "^7.0.2",
    "eslint": "^6.8.0",
    "eslint-config-prettier": "^6.7.0",
    "eslint-config-standard": "^14.1.0",
    "eslint-config-standard-react": "^9.2.0",
    "eslint-plugin-import": "^2.18.2",
    "eslint-plugin-node": "^11.0.0",
    "eslint-plugin-prettier": "^3.1.1",
    "eslint-plugin-promise": "^4.2.1",
    "eslint-plugin-react": "^7.17.0",
    "eslint-plugin-react-hooks": "^4.2.0",
    "eslint-plugin-standard": "^4.0.1",
    "gh-pages": "^2.2.0",
    "microbundle-crl": "^0.13.10",
    "node-sass": "^5.0.0",
    "npm-run-all": "^4.1.5",
    "prettier": "^2.0.4",
    "prop-types": "^15.7.2",
    "react": "^16.13.1 || ^17.0.2",
    "react-dom": "^16.13.1 || ^17.0.2",
    "react-scripts": "^3.4.1",
    "react-test-renderer": "^17.0.1 || ^17.0.2"
  },

npm install doesnt work on react-gallery-carousel/example/

Describe the bug
I managed to install dependencies but I still get this error:

./src/components/Carousel1.js
Cannot find file: 'TwoWayMap.js' does not match the corresponding name on disk: '.\src\utils\twoWayMap.js'.

And there is no such file under \utils\

To Reproduce

npm install
npm start

Fix
import TwoWayMap from '../utils/TwoWayMap';
needs to be
import TwoWayMap from '../utils/twoWayMap';

Add SSR support

Please consider adding support for server-side rendering (SSR).

Here's what I got using your perfect (it is!) carousel with Gatsby:

"document" is not available during server side rendering.

See our docs page for more info on this error: https://gatsby.dev/debug-html

  2686 | var GalleryCarousel = function GalleryCarousel(props, ref) {
> 2687 |   var documentRef = useRef(document);
       |                           ^
  2688 |   var maximizedBackgroundRef = useRef(null);
  2689 |   var carouselRef = useRef(null);
  2690 |   var slidesContainerRef = useRef(null);


  WebpackError: ReferenceError: document is not defined

  - index.modern.js:2687
    [sns-front]/[react-gallery-carousel]/dist/index.modern.js:2687:27

Touch-swiping does not work if the images are dynamically set in useEffect

Describe the bug
Touch-swiping does not work on the slides when the images are dynamically set in the useEffect() hook by developer users.

To Reproduce
Steps to reproduce the behavior:

  1. Make a carousel and set the images in useEffect()
  2. Swipe the slides part of the carousel (the slides part is in contract with the optional thumbnails part)
  3. See error that touch-swiping does not work

Expected behavior
Touch swiping should work even if the images are dynamically set.

Screenshots
The GIF below is taken from the initial loading to the occurrence of the bug.
Carousel does not respond to touch swiping

Desktop (please complete the following information):

  • macOS
  • Chrome
  • Version 89.0.4389.90 (Official Build) (x86_64)

Not working on IOS/Safari

The gallery is not working under IPhone/Safari, it shows following error message:

mediaQueryList.addEventListener is not a function. (In 'mediaQueryList.addEventListener('change', callback)', 'mediaQueryList.addEventListener' is undefined)

Apparently the window.matchMedia(query) does not have addEventListener/removeEventListener on some browsers.

This is called in one useSellect in react-gallery-carousel:

image

If you don't have IOS, I can recommend you to try https://www.browserstack.com/, you can test there a little bit for free, or you can use some other IOS emulator

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.