GithubHelp home page GithubHelp logo

xiaolin / react-image-gallery Goto Github PK

View Code? Open in Web Editor NEW
3.7K 40.0 706.0 52.85 MB

React carousel image gallery component with thumbnail support ๐Ÿ–ผ

Home Page: http://linxtion.com/demo/react-image-gallery

License: MIT License

CSS 3.25% JavaScript 86.46% HTML 0.49% SCSS 9.80%
image-gallery carousel slide-images react-components react image-slider gallery react-carousel react-image-gallery react-image-slider

react-image-gallery's Introduction

React Image Gallery

npm version Download Count Bundle size

Live Demo (try it on mobile for swipe support)

linxtion.com/demo/react-image-gallery

demo gif

React image gallery is a React component for building image galleries and carousels

Features

  • Mobile swipe gestures
  • Thumbnail navigation
  • Fullscreen support
  • Custom rendered slides
  • RTL support
  • Responsive design
  • Tons of customization options (see props below)

Getting started

React Image Gallery requires React 16.0.0 or later.

npm install react-image-gallery

Style import options

# scss file import
@import "~react-image-gallery/styles/scss/image-gallery.scss";

# css file import
@import "~react-image-gallery/styles/css/image-gallery.css";

# js file import (using webpack)
import "react-image-gallery/styles/css/image-gallery.css";

Example

Need more example? See example/app.js

import ImageGallery from "react-image-gallery";
// import stylesheet if you're not already using CSS @import
import "react-image-gallery/styles/css/image-gallery.css";

const images = [
  {
    original: "https://picsum.photos/id/1018/1000/600/",
    thumbnail: "https://picsum.photos/id/1018/250/150/",
  },
  {
    original: "https://picsum.photos/id/1015/1000/600/",
    thumbnail: "https://picsum.photos/id/1015/250/150/",
  },
  {
    original: "https://picsum.photos/id/1019/1000/600/",
    thumbnail: "https://picsum.photos/id/1019/250/150/",
  },
];

class MyGallery extends React.Component {
  render() {
    return <ImageGallery items={images} />;
  }
}

Props

  • items: (required) Array of objects, see example above,

    • Available Properties
      • original - image src url
      • thumbnail - image thumbnail src url
      • fullscreen - image for fullscreen (defaults to original)
      • originalHeight - image height (html5 attribute)
      • originalWidth - image width (html5 attribute)
      • loading - image loading. Either "lazy" or "eager" (html5 attribute)
      • thumbnailHeight - image height (html5 attribute)
      • thumbnailWidth - image width (html5 attribute)
      • thumbnailLoading - image loading. Either "lazy" or "eager" (html5 attribute)
      • originalClass - custom image class
      • thumbnailClass - custom thumbnail class
      • renderItem - Function for custom rendering a specific slide (see renderItem below)
      • renderThumbInner - Function for custom thumbnail renderer (see renderThumbInner below)
      • originalAlt - image alt
      • thumbnailAlt - thumbnail image alt
      • originalTitle - image title
      • thumbnailTitle - thumbnail image title
      • thumbnailLabel - label for thumbnail
      • description - description for image
      • srcSet - image srcset (html5 attribute)
      • sizes - image sizes (html5 attribute)
      • bulletClass - extra class for the bullet of the item
  • infinite: Boolean, default true

    • infinite sliding
  • lazyLoad: Boolean, default false

  • showNav: Boolean, default true

  • showThumbnails: Boolean, default true

  • thumbnailPosition: String, default bottom

    • available positions: top, right, bottom, left
  • showFullscreenButton: Boolean, default true

  • useBrowserFullscreen: Boolean, default true

    • if false, fullscreen will be done via css within the browser
  • useTranslate3D: Boolean, default true

    • if false, will use translate instead of translate3d css property to transition slides
  • showPlayButton: Boolean, default true

  • isRTL: Boolean, default false

    • if true, gallery's direction will be from right-to-left (to support right-to-left languages)
  • showBullets: Boolean, default false

  • showIndex: Boolean, default false

  • autoPlay: Boolean, default false

  • disableThumbnailScroll: Boolean, default false

    • disables the thumbnail container from adjusting
  • disableKeyDown: Boolean, default false

    • disables keydown listener for keyboard shortcuts (left arrow, right arrow, esc key)
  • disableSwipe: Boolean, default false

  • disableThumbnailSwipe: Boolean, default false

  • onErrorImageURL: String, default undefined

    • an image src pointing to your default image if an image fails to load
    • handles both slide image, and thumbnail image
  • indexSeparator: String, default ' / ', ignored if showIndex is false

  • slideDuration: Number, default 450

    • transition duration during image slide in milliseconds
  • swipingTransitionDuration: Number, default 0

    • transition duration while swiping in milliseconds
  • slideInterval: Number, default 3000

  • slideOnThumbnailOver: Boolean, default false

  • flickThreshold: Number (float), default 0.4

    • Determines the max velocity of a swipe before it's considered a flick (lower = more sensitive)
  • swipeThreshold: Number, default 30

    • A percentage of how far the offset of the current slide is swiped to trigger a slide event. e.g. If the current slide is swiped less than 30% to the left or right, it will not trigger a slide event.
  • stopPropagation: Boolean, default false

    • Automatically calls stopPropagation on all 'swipe' events.
  • startIndex: Number, default 0

  • onImageError: Function, callback(event)

    • overrides onErrorImage
  • onThumbnailError: Function, callback(event)

    • overrides onErrorImage
  • onThumbnailClick: Function, callback(event, index)

  • onBulletClick: Function, callback(event, index)

  • onImageLoad: Function, callback(event)

  • onSlide: Function, callback(currentIndex)

  • onBeforeSlide: Function, callback(nextIndex)

  • onScreenChange: Function, callback(boolean)

    • When fullscreen is toggled a boolean is passed to the callback
  • onPause: Function, callback(currentIndex)

  • onPlay: Function, callback(currentIndex)

  • onClick: Function, callback(event)

  • onTouchMove: Function, callback(event) on gallery slide

  • onTouchEnd: Function, callback(event) on gallery slide

  • onTouchStart: Function, callback(event) on gallery slide

  • onMouseOver: Function, callback(event) on gallery slide

  • onMouseLeave: Function, callback(event) on gallery slide

  • additionalClass: String,

    • Additional class that will be added to the root node of the component.
  • renderCustomControls: Function, custom controls rendering

    • Use this to render custom controls or other elements on the currently displayed image (like the fullscreen button)
      _renderCustomControls() {
        return <a href='' className='image-gallery-custom-action' onClick={this._customAction.bind(this)}/>
      }
  • renderItem: Function, custom item rendering

    • NOTE: Highly suggest looking into a render cache such as React.memo if you plan to override renderItem
    • On a specific item [{thumbnail: '...', renderItem: this.myRenderItem}]
    • As a prop passed into ImageGallery to completely override renderItem, see source for renderItem implementation
  • renderThumbInner: Function, custom thumbnail rendering

    • On a specific item [{thumbnail: '...', renderThumbInner: this.myRenderThumbInner}]
    • As a prop passed into ImageGallery to completely override _renderThumbInner, see source for reference
  • renderLeftNav: Function, custom left nav component

    • See <LeftNav />
    • Use this to render a custom left nav control
    • Args:
      • onClick callback that will slide to the previous item
      • disabled boolean for when the nav is disabled
    renderLeftNav: (onClick, disabled) => (
      <LeftNav onClick={onClick} disabled={disabled} />
    );
  • renderRightNav: Function, custom right nav component

    • See <RightNav />
    • Use this to render a custom right nav control
    • Args:
      • onClick callback that will slide to the next item
      • disabled boolean for when the nav is disabled
    renderRightNav: (onClick, disabled) => (
      <RightNav onClick={onClick} disabled={disabled} />
    );
  • renderPlayPauseButton: Function, play pause button component

    • See <PlayPause />
    • Use this to render a custom play pause button
    • Args:
      • onClick callback that will toggle play/pause
      • isPlaying boolean for when gallery is playing
    renderPlayPauseButton: (onClick, isPlaying) => (
      <PlayPause onClick={onClick} isPlaying={isPlaying} />
    );
  • renderFullscreenButton: Function, custom fullscreen button component

    • See <Fullscreen />
    • Use this to render a custom fullscreen button
    • Args:
      • onClick callback that will toggle fullscreen
      • isFullscreen argument for when fullscreen is active
      renderFullscreenButton: (onClick, isFullscreen) => (
        <Fullscreen onClick={onClick} isFullscreen={isFullscreen} />
      ),
  • useWindowKeyDown: Boolean, default true

    • If true, listens to keydown events on window (window.addEventListener)
    • If false, listens to keydown events on image gallery element (imageGalleryElement.addEventListener)

Functions

The following functions can be accessed using refs

  • play(): plays the slides
  • pause(): pauses the slides
  • toggleFullScreen(): toggles full screen
  • slideToIndex(index): slides to a specific index
  • getCurrentIndex(): returns the current index

Contributing

Each pull request (PR) should be specific and isolated to the issue you're trying to fix. Please do not stack features, chores, refactors, or enhancements in one PR. Describe your feature/implementation in the PR. If you're unsure whether it's useful or if it involves a major change, please open an issue first and seek feedback.

  • Follow eslint provided
  • Comment your code
  • Write clean code

Build the example locally (requires node >= 12.13)

git clone https://github.com/xiaolin/react-image-gallery.git
cd react-image-gallery
npm install --global yarn
yarn install
yarn start

Then open localhost:8001 in a browser.

License

MIT

react-image-gallery's People

Contributors

4muzar avatar alexmeah avatar antonioyon avatar austinleegordon avatar codematix avatar danielravina avatar daryawood avatar dentrado avatar dependabot[bot] avatar gaborluk avatar grifotv avatar hartzis avatar hendrik avatar huksley avatar ignorancepulls avatar insprill avatar jblissbonobos avatar johannesd avatar kamui avatar luo-yihang avatar markomarkom avatar mattdell avatar michalklim avatar mikkom avatar nicohaemhouts avatar peralmq avatar twanschik avatar vntw avatar vzaidman avatar xiaolin 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  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

react-image-gallery's Issues

Sass partial should start with underscore

I'm using sass-loader 1.x (webpack) and get the following error:

ERROR in ./~/css-loader!./~/sass-loader!./app/style/style.scss
Module build failed: 
@import "../node_modules/react-image-gallery/src/ImageGallery.scss";
       ^
      File to import not found or unreadable: ../node_modules/react-image-gallery/src/_ImageGallery.scss

According to the specs, sass @imports should start with an underscore, so I would suggest you rename ImageGallery.scss to _ImageGallery.scss since it's a partial.

Thumbnails should scroll vertically too.

Right now I see you have only translateX.

I am using this plugin and I have requirement where I need to translateY.

Would you be kind enough to implement this feature :)

onTouchStart results in unexpected behavior

With this line in place, merely scrolling past the image gallery with the scrolling finger touching the area of the gallery will result in the triggering of the custom onClick method, which, in turn, might do things like opening a larger image on a modal; a very unexpected behavior and frustrating user experience.

The onClick should trigger just fine on tap events on touch devices, there is no need to specify a separate onTouchStart if the goal is simply to make sure that the custom onClick method works on these devices. Is there any other reason for having included this line, or is it safe to remove it?

React v15 throws 'Unknown props' Warning

After upgrading react to 15.2.1 I get the following warning:

Warning: Unknown props `delta`, `onSwipingLeft`, `onSwipingRight`, `onSwiped`, `onSwipedLeft`, `onSwipedRight`, `flickThreshold`, `preventDefaultTouchmoveEvent`, `nodeName` on <div> tag. Remove these props from the element. For details, see https://fb.me/react-unknown-prop
    in div (created by Swipeable)
    in Swipeable (created by ImageGallery)
    in div (created by ImageGallery)
    in section (created by ImageGallery)
    in ImageGallery (created by MyComponent)
    in div (created by MyComponent)

Warning references: https://fb.me/react-unknown-prop
See following issues:
facebook/react#7163
mui/material-ui#4594

Slide no longer works

After updating to the latest version to resolve the issue of sliding to the left in the event that there were only two images, slide no longer works.

Can I handle Clicks

I need to open links when image or description is clicked.
Is there anyway to do this?

Referencing Vidoe and Audio file

First of all, this is an amazing react solution.

Is it possible to reference video and Audio files. If not is there flexibility to customize this plugin to handle vidoe and audio files.

Thank you.

Support for fallback images if image not loaded

It would be great if the gallery would support fallback images for both active and thumbnail images in case any of them fail to load. Like:

<ImageGallery
    items={images}
    defaultImage="/img/notFound.png"/>

Could you please check this issue?

Warning: ReactDOMComponent: Do not access .props of a DOM node; instead, recreate the props as render did originally or read the DOM properties/attributes directly from this node (e.g., this.refs.box.className). This DOM node was rendered by ImageGallery.

thumbnail container width < 100%

Trying to get the navigation arrows at the bottom (on either side of the thumbnails). Positioning them works, but it means the thumbnails at the end get covered by the arrows.

Due to thumbnail translateX using galleryWidth instead of thumbnailContainer width - probably same fix as for #76

Router support?

Hi @xiaolin! Thank you for the component?

I am wondering what your thoughts are on adding router support, i.e. updating the url when navigating left to right?

Auto-detect props.items changes

At the moment, changing props.items won't reset state.currentIndex automatically, so that props.items changes can result in a broken image. The current workaround is to use slideToIndex to reset the currentIndex back to the correct start position on props.items changes.

It's possible to auto-detect props.items changes by comparing the current and next props.items arrays. However, the solution I'm using on my fork adds 2 more dependencies to the project (immutable and immutablediff), so that there's quite a bit of extra code just to have the ability to compare the property changes. That's also the reason I didn't submit a pull request for this, as I don't know whether you would want to add such extra dependencies to the original code base.

I mentioned about sharing my solution in one of the previous commit messages, so here are the relevant changes from my build/image-gallery.js file:

  var diff = require('immutablediff');
  var Immutable = require('immutable');

  ...  

  componentWillReceiveProps: function componentWillReceiveProps(nextProps) {
    var propsDiff = diff(Immutable.fromJS(this.props.items), Immutable.fromJS(nextProps.items));
    if (propsDiff.size !== 0) {
      var startIndex = nextProps.startIndex || 0;
      this.setState({ currentIndex: startIndex });
    }
  }

npm package broken

I believe the 0.4.9 and 0.5.0 releases are broken because your package.json main key points to ./build/image-gallery which was removed when you bumped to 0.4.9

Image height affects component height

My images have different sizes and when I'm scrolling through them, the height of the component changes. Is there a way to make the image viewport of a static height?

React 0.14.0 warning

Since I switched to React v0.14.0 I get fallowing warnings:

Warning: ImageGallery.getDOMNode(...) is deprecated. Please use ReactDOM.findDOMNode(instance) instead.warning @ main.js:2231
main.js:2231 Warning: ReactDOMComponent: Do not access .getDOMNode() of a DOM node; instead, use the node directly. This DOM node was rendered by ImageGallery.

Unexpected sliding direction in a 2-image gallery

When the gallery only contains a total of 2 images, sliding direction is the opposite of what you would expect based on the order of the thumbnails. For example, when image #1 is active, and you click thumbnail #2, you would expect that image #1 slides out to the left, and image #2 slides in from the right, however, it happens the other way around. Similarly, swiping left on image #1 results in a bounce and slide backwards, arriving on image #2.

I haven't had time to look into this in detail, but if nobody picks it up and you don't have time either, @xiaolin, I might track this down sometime next week.

getCurrentIndex() returns 'not a function'

Was trying getCurrentIndex() function and it keeps returning me Uncaught TypeError: _this._imageGallery.getCurrentIndex is not a function
I tried to console out this._imageGallery and i get the component but i dont see any open function with getCurrentIndex()

I am on version ^0.6.1

Console out of this._imageGallery

react-image-gallery

Doesn't work as expected when images array length is 1

First I would like to thank you for your work.

When I pass images as an array that contains only one object, the slider doesn't work as expected.
The div with class image-gallery-slide is translated by transform: translate3d(-100%, 0px, 0px);, leading the image to slide to the left and the slider displays nothing.

Is there a way to get this to work as expected by displaying the only image ?

Error loading build css on latest react/webpack versions

Error is:
ERROR in ./~/react-image-gallery/build/image-gallery.css Module parse failed: .../node_modules/react-image-gallery/build/image-gallery.css Unexpected character '@' (1:0)

If you remove:
@charset "UTF-8";
it works ok.

Cannot find module 'react/addons'

When I
var ImageGallery = require('react-image-gallery');
I get: Cannot find module 'react/addons'

I have to require the whole src path like this:
var ImageGallery = require('react-image-gallery/src/ImageGallery.react.jsx');
To get it to work.

Don't show arrows (Feature request)

It would be great to be able to control showing navigation arrows, the same way that now I could decide showing the bullets and thumbnails with showBullets and showThumbnails.

How to use the renderItem prop?

Hi, first of all, thanks for a neat image carousel/gallery react component.

This is not really an issue but rather a question on how to use the renderItem prop.
What I would like to do is to modify the content of the item.description to have some links into it.

Appreciate your response to this.

Thanks!

Cannot set property '_preventGhostClick' of null (in _touchEnd method)

Using this plugin on a touch supported device will get this bug, on the line:

https://github.com/xiaolin/react-image-gallery/blob/master/src/ImageGallery.react.jsx#L128

with react 0.14.0 and react-image-gallery 0.5.11. My config file is kind like the example file:

https://github.com/xiaolin/react-image-gallery/blob/master/example/app.js

I use the react developer tool to detect the "showNav" state, this is mine:

and this is the demo's:

seemed I missed some steps, the bind method didn't work to the element.

I'm not sure where am I wrong. Any suggestions?

Thanks.

Responsive Images

Is there a way to load different sized images based on the view port.

I.e. Not have the client download the high-res when they are on a phone.

Thanks

many deprecation warnings

Im using react 15.3.0:

Warning: You are manually calling a React.PropTypes validation function for the itemsprop onImageGallery. This is deprecated and will not work in the next major version. You may be seeing this warning due to a third-party PropTypes library. See https://fb.me/react-warning-dont-call-proptypes for details.

and many more, all about manually calling PropTypes

Add swipe support

It will be great if the thumbnails section have a smoother swipe support.

About startIndex and onSlide event handler

Hi @xiaolin,
When I play image over than 15 items, and start index is last two item. the player will start in error index.
Ex: I hope start index is 14, but final player start in 7 or 8. And I found the "onSlide" has been trigger twice. It will work as normal, when I play images with index 0~12( onSlide just trigger once when initial )
After player initialized, it can work as normal(onSlide will trigger once, when I click thumbnail of nav, or by touch slide event)
I cannot finger out the root cause, or maybe I just set wrong configuration?

My sample code:

    state:{
       imgArray : [{image_info}, {image_info}, {image_info}, ...]; //15 images 
    }
    <ImageGallery
                ref={i => this._imageGallery = i}
                startIndex={this.state.currentIndex}
                infinite={false}
                lazyLoad={true}
                showNav={false}
                showThumbnails={true}
                items={this.state.imgArray }
                onImageLoad={this.handleImageLoad}
                onSlide={this.handleSlide.bind(this)}
                onClick={this.handleClick.bind(this)}
     />
 handleSlide and handleClick just print log, no more else action.

If you need more information, please let me know.
I hope you can help me to solve this problem, thanks.
:)

Kevin

Add support for initial image

Support an initial image attribute which displays the image at the specified index initially when the gallery component is mounted.

Below example, loads the 3rd image initially

<ImageGallery items={images}
                        initialImage={2}/>

AutoScroll stops on android device after clicking on image

First of all, the component is wonderful.
Easy to use example, good demo, all you need to know is documented.
Good job.
I used component like this:

<ImageGallery
  ref={i => this._imageGallery = i}
  items={slides}
  infinite={true}
  showThumbnails={false}
  showNav={false}
  showBullets={true}
  autoPlay={true}
  slideInterval={SLIDER_AUTOPLAY_TIMEOUT}
  onClick={this.handleOnClick}
/>

On Android device automatic scrolling of images working fine until i touch the image itself (not the bullet).
If i touch the image i'll see onClick event and after that automatic scrolling is stop working.

handleOnClick() {
  this._imageGallery.setState({
    hovering: false
  });
  this._imageGallery.play(this._imageGallery.state.currentIndex);
},

Adding the code above solved the problem, but i wonder is this a good solution and why this behavior reproducible only on Android, but not on iOS. Is there an easiest way to solve the problem i'm talking about?

currentIndex not set when received new props

Hi,

I noticed the following code has been removed some time ago

componentWillReceiveProps(nextProps) {
  if (this.props.items.length !== nextProps.items.length) {
    const startIndex = nextProps.startIndex || 0
    this.setState({currentIndex: startIndex})
  }
}

Right now, when new props arrive, currentIndex stays as before. Hence when nextProps has more items than before, the gallery shows no image. I guess currentIndex should be reset in this case or is there some other way to do it right now?

Cannot Get Property Length

I've noticed that I was receiving this error with react 0.13.3 :
Uncaught TypeError: Cannot read property 'length' of undefined

I realized that it was not correctly getting the thumbnail count from this portion of the code:

if (this.refs.thumbnails) {
      var thumbNode = this.refs.thumbnails;
      if (thumbNode.scrollWidth <= this.state.containerWidth) {
        return 0;
      }

      var totalThumbnails = thumbNode.children.length;

      // total scroll-x required to see the last thumbnail
      var totalScrollX = thumbNode.scrollWidth - this.state.containerWidth;

      // scroll-x required per index change
      var perIndexScrollX = totalScrollX / (totalThumbnails - 1);

      return indexDifference * perIndexScrollX;
    }

In turn I updated :

var totalThumbnails = thumbNode.children.length TO: var totalThumbnails = thumbNode.props.children.length

This solves my issue. I don't know if you want that changed / or if you want to support 0.13.3

Thanks

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.