Git Product home page Git Product logo

lightbox-react's Introduction

React Component & Image Lightbox

NPM

A lightbox for React components or images. String passed as arguments are assumed to be the src for an image. Otherwise, it will check if the argument is able to be rended as a child React component of the lightbox.

DEMO

Originally forked from fritz-c's library

Features

  • Keyboard shortcuts (with rate limiting)
  • Image Zoom
  • Flexible rendering using src values assigned on the fly
  • Image preloading for smoother viewing
  • Mobile friendly, with pinch to zoom and swipe (Thanks, @webcarrot!)
  • No external CSS

Example

import React, { Component } from 'react';
import Lightbox from 'lightbox-react';
import 'lightbox-react/style.css'; // This only needs to be imported once in your app

import VideoIframe from 'components/video';

const images = [
  VideoIframe,
  '//placekitten.com/1500/500',
  '//placekitten.com/4000/3000',
  '//placekitten.com/800/1200',
  '//placekitten.com/1500/1500',
];

export default class LightboxExample extends Component {
  constructor(props) {
    super(props);

    this.state = {
      photoIndex: 0,
      isOpen: false,
    };
  }

  render() {
    const { photoIndex, isOpen } = this.state;

    return (
      <div>
        <button type="button" onClick={() => this.setState({ isOpen: true })}>
          Open Lightbox
        </button>

        {isOpen && (
          <Lightbox
            mainSrc={images[photoIndex]}
            nextSrc={images[(photoIndex + 1) % images.length]}
            prevSrc={images[(photoIndex + images.length - 1) % images.length]}
            onCloseRequest={() => this.setState({ isOpen: false })}
            onMovePrevRequest={() =>
              this.setState({
                photoIndex: (photoIndex + images.length - 1) % images.length,
              })
            }
            onMoveNextRequest={() =>
              this.setState({
                photoIndex: (photoIndex + 1) % images.length,
              })
            }
          />
        )}
      </div>
    );
  }
}

Deprecation Notice

All unprefixed classes (listed below) will be removed in v4.0.0. Use their ril- prefixed alternatives instead. close, closing, download-blocker, image-current, image-next, image-prev, inner, next-button, not-loaded, outer, prev-button, toolbar, toolbar-left, toolbar-right, zoom-in, zoom-out

Options

Property Type Default Required Description
mainSrc string yes Main display image url or React component
prevSrc string Previous display image url or component (displayed to the left). If left undefined, onMovePrevRequest will not be called, and the button not displayed
nextSrc string Next display image url or component (displayed to the right). If left undefined, onMoveNextRequest will not be called, and the button not displayed
mainSrcThumbnail string Thumbnail image url corresponding to props.mainSrc. Displayed as a placeholder while the full-sized image loads.
prevSrcThumbnail string Thumbnail image url corresponding to props.prevSrc. Displayed as a placeholder while the full-sized image loads.
nextSrcThumbnail string Thumbnail image url corresponding to props.nextSrc. Displayed as a placeholder while the full-sized image loads.
onCloseRequest func yes Close window event. Should change the parent state such that the lightbox is not rendered
onMovePrevRequest func empty function Move to previous image event. Should change the parent state such that props.prevSrc becomes props.mainSrc, props.mainSrc becomes props.nextSrc, etc.
onMoveNextRequest func empty function Move to next image event. Should change the parent state such that props.nextSrc becomes props.mainSrc, props.mainSrc becomes props.prevSrc, etc.
onImageLoadError func empty function Called when an image fails to load.
<code>(imageSrc: string, srcType: string, errorEvent: object): void</code>
discourageDownloads bool false Enable download discouragement (prevents [right-click -> Save Image As...])
animationDisabled bool false Disable all animation
animationOnKeyInput bool false Disable animation on actions performed with keyboard shortcuts
animationDuration number 300 Animation duration (ms)
keyRepeatLimit number 180 Required interval of time (ms) between key actions (prevents excessively fast navigation of images)
keyRepeatKeyupBonus number 40 Amount of time (ms) restored after each keyup (makes rapid key presses slightly faster than holding down the key to navigate images)
imageTitle node Image title (Descriptive element above image)
imageCaption node Image caption (Descriptive element below image)
toolbarButtons node[] Array of custom toolbar buttons
reactModalStyle Object {} Set z-index style, etc., for the parent react-modal (react-modal style format)
imagePadding number 10 Padding (px) between the edge of the window and the lightbox
clickOutsideToClose bool true When true, clicks outside of the image close the lightbox
enableZoom bool true Set to false to disable zoom functionality and hide zoom buttons

Browser Compatibility

Browser Works?
Chrome Yes
Firefox Yes
Safari Yes
IE >= 10 Yes
IE 9 Everything works, but no animations

Contributing

After cloning the repository and running npm install inside, you can use the following commands to develop and build the project.

# Starts a webpack dev server that hosts a demo page with the lightbox.
# It uses react-hot-loader so changes are reflected on save.
npm start

# Lints the code with eslint and my custom rules.
npm run lint

# Lints and builds the code, placing the result in the dist directory.
# This build is necessary to reflect changes if you're
#  `npm link`-ed to this repository from another local project.
npm run build

Pull requests are welcome!

License

MIT

lightbox-react's People

Contributors

dependabot[bot] avatar treyhuffine 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

Watchers

 avatar  avatar  avatar  avatar

lightbox-react's Issues

ClickOutsideToClose when using Component

Hi Trey,

Thanks for extending this module to work with components!

I noticed that ClickOutsideToClose does not work if the item is a component. It looks like that's because the div with the .ril-current-image class is not receiving a width when the child is not an image and as a result is taking up 100%, preventing the user from clicking outside the media visible to close the Lightbox. You can see an example of this in your demo, when viewing the YT iframe slide.

Would it be possible to fix this by automatically detecting the width of the child component's parent element or somehow passing it in when the child is not an image?

I guess the alternative would be to set some width smaller than 100% on the class in CSS to always have some room around the media.

Thanks,
Anatoly

Whole site crashes ios iphone

I just found this bug but it happens when you click on a very large image to open the light box
some info on the environment
gatsby site
light box is inside of a popup modal made from https://github.com/reactjs/react-modal

// https://www.npmjs.com/package/lightbox-react
import React from 'react'
import Lightbox from 'lightbox-react'
import 'lightbox-react/style.css'

import style from './photoarray.module.sass'
class photoArray extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      photoIndex: 0,
      isOpen: false,
      images: [],
    }
    this.buildarray = this.buildarray.bind(this)
  }
  buildarray() {
    const tempArray = []
    this.props.imageArray.forEach(element => {
      tempArray.push(element.src)
    })
    tempArray.push(this.props.altImage.src)
    this.setState({ images: tempArray })
  }
  componentDidMount() {
    this.buildarray()
  }

  render() {
    const { photoIndex, isOpen } = this.state
    return this.state.images.map((img, index) => (
      <div className={style.img__wrapper}>
        <img
          key={index}
          src={img}
          alt=""
          onClick={() => this.setState({ isOpen: true })}
        />
        {isOpen && (
          <Lightbox
            mainSrc={this.state.images[photoIndex]}
            nextSrc={
              this.state.images[(photoIndex + 1) % this.state.images.length]
            }
            prevSrc={
              this.state.images[
                (photoIndex + this.state.images.length - 1) %
                  this.state.images.length
              ]
            }
            onCloseRequest={() => this.setState({ isOpen: false })}
            onMovePrevRequest={() =>
              this.setState({
                photoIndex:
                  (photoIndex + this.state.images.length - 1) %
                  this.props.imageArray.length,
              })
            }
            onMoveNextRequest={() =>
              this.setState({
                photoIndex: (photoIndex + 1) % this.state.images.length,
              })
            }
          />
        )}
      </div>
    ))
  }
}

export default photoArray

image1
image2

I don't know if its connected but but on the other light box I have on this site that has smaller photos in it they work but only kinda

image3
image2 1
image1 1

I just wanted to know if this is a known bug? Or maybe its just something I'm doing wrong

EXIF data of an image is ignored, wrong image orientation

ios camera adds EXIF meta-data to the images.
This data can contain information about image rotation.
But lightbox-react ignores it.
When you try to display vertical photographs, uploaded from ios camera, on some other platforms: linux chrome, android and much more, image is rotated, stretched.

Problem most definitely connected with html img src default behavior: https://stackoverflow.com/questions/24658365/img-tag-displays-wrong-orientation

But in my opinion, plugin should cover those cases.

Is there any possibility to customize the functions inside the component or at least pass an config object which allows to pass some functions to run instead of given methods.

I have a requirement to display tables in the light box and also make it accessible.In order to do that since there is no flexibility to override the functions inside the component , I had to think of go ahead and edit the functions which stops me to use the latest versions of the light box. Is there approach I can use to resolve this issue?.thanks

No support for Components anymore in 0.3.6?

I am using the Lightbox v 0.3.6 and when using React Components as Lightbox Sources it says:

warning.js:33 Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: object.

Check the render method of `ArtistDetail`.
    in ArtistDetail (created by I18n)
    in I18n (created by Translate(ArtistDetail))
    in Translate(ArtistDetail) (created by Query)
    in Query (created by Apollo(Translate(ArtistDetail)))
    in Apollo(Translate(ArtistDetail)) (created by Query)
    in Query (created by Apollo(Apollo(Translate(ArtistDetail))))
    in Apollo(Apollo(Translate(ArtistDetail))) (created by Route)
    in Route (created by App)
    in Switch (created by App)
    in Provider (created by App)
    in main (created by App)
    in App (created by Route)
    in Route (created by withRouter(App))
    in withRouter(App)
    in I18nextProvider
    in Router (created by BrowserRouter)
    in BrowserRouter
    in Provider
    in ApolloProvider

Code:

const lightBoxSources = props.artistDetail.route.entity.fieldWannaDoS.map((item, index) =>
      <Overlay
        img={item.entity.fieldMediaImage.image}
        heading={props.artistDetail.route.entity.title}
        url={props.match.url}
        themes={item.entity.fieldStyle}
        index={item.entity.fieldMediaImage.targetId}
        key={index}
        language={props.location.pathname.split('/')[1]}
        lightBoxType={'wannados'}
        close={this.closeOverlayWannaDos}
      />
    );

iframe component does not render anything

lightbox-react:
^0.3.7

Code:

import React, { Component } from 'react';
import Lightbox from 'lightbox-react';
import 'lightbox-react/style.css';

const Video = () => (
  <iframe
    title="cats"
    width="560"
    height="315"
    src="https://www.youtube.com/embed/5dsGWM5XGdg"
    style={{
      maxWidth: '97%',
      position: 'absolute',
      left: 0,
      right: 0,
      margin: 'auto',
      top: '50%',
      transform: 'translateY(-50%)',
    }}
  />
);

const images = [
  Video,
  '//placekitten.com/1500/500',
  '//placekitten.com/4000/3000',
  '//placekitten.com/800/1200',
  '//placekitten.com/1500/1500',
];

export class LightboxComponent extends Component {
  constructor(props) {
    super(props);

    this.state = {
      photoIndex: 0,
      isOpen: false,
    };
  }

  render() {
    const { photoIndex, isOpen } = this.state;

    return (
      <div>
        <button type="button" onClick={() => this.setState({ isOpen: true })}>
          Open Lightbox
        </button>

        {isOpen && (
          <Lightbox
            mainSrc={images[photoIndex]}
            nextSrc={images[(photoIndex + 1) % images.length]}
            prevSrc={images[(photoIndex + images.length - 1) % images.length]}
            onCloseRequest={() => this.setState({ isOpen: false })}
            onMovePrevRequest={() =>
              this.setState({
                photoIndex: (photoIndex + images.length - 1) % images.length,
              })
            }
            onMoveNextRequest={() =>
              this.setState({
                photoIndex: (photoIndex + 1) % images.length,
              })
            }
          />
        )}
      </div>
    );
  }
}

export default LightboxComponent;

Effect:
images inside ril-inner are rendered correctly, but div with iframe does not appear inside ril-inner.

<div class="ril-inner ril__inner">

  <!-- <div> with <iframe> does not appear here -->

  <img class="ril-image-current ril__image" ... />
  <img class="ril-image-prev ril__imagePrev ril__image" ... />
</div>

Everything works fine on the demo page (iframe with div appear inside ril-inner) http://treyhuffine.com/lightbox-react/

<div class="inner ril-inner inner___1rfRQ">
  <img class="image-next ril-image-next imageNext___1uRqJ image___2FLq2" ... />

  <!-- it is OK! -->
  <div class="image-current ril-image-current image___2FLq2">
    <iframe ...></iframe>
  </div>

  <img class="image-prev ril-image-prev imagePrev___F6xVQ image___2FLq2" .../>
</div>

I can not tell what are the differences between the version presented on the demo and v0.3.7. If anyone knows, please let me know :)

Incorrect Peer Dependencies

Hi,

I've upgraded to react 16.4 which now causes "incorrect peer dependency" warnings with this package (see below). Just wondering if this package is still being maintained or if anyone can give advice how to correct these issues?

warning " > [email protected]" has incorrect peer dependency "react@^15.0.0".
warning " > [email protected]" has incorrect peer dependency "react-dom@^15.0.0".
warning "lightbox-react > [email protected]" has incorrect peer dependency "react@^0.14.0 || ^15.0.0".
warning "lightbox-react > [email protected]" has incorrect peer dependency "react-dom@^0.14.0 || ^15.0.0".

Cheers

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.