Search code examples
reactjsreact-slick

How to add touch-enabled lightbox features to [react-slick]?


I've recently moved to React after building sites which used jQuery plugins to provide most functionality. To create an image slider + lightbox, I used to combine slick.js with halkaBox.js or SimpleLightbox (which was pretty easy).

Now that I'm using React, I've found react-slick to be a great slider component, but I'm not sure how best to add touch-enabled lightbox functionality to it. Is there a touch-enabled React lightbox component that pairs well with react-slick? Is there a proper way incorporate a JS plugin like halkaBox.js with a React component like react-slick?

Any guidance would be appreciated!


Solution

  • I think, you can use react-slick + react-image-lightbox. Local state is a good place to save path of the current image;

    import Slider from 'react-slick';
    import Lightbox from 'react-image-lightbox';
    
    class Slider extends React.Component{
      constructor(props){
        super(props);
    
        this.state = {
          images: ['src/image1.png', 'src/image2.png', 'src/image3.png'],
          current: ''
        }
      }
    
      getSliderSettings(){
       return {
          dots: true,
          infinite: true,
          speed: 500,
          slidesToShow: 1,
          slidesToScroll: 1
       }
      }
    
      handleClickImage = (e, image) => {
       e && e.preventDefault();
    
       this.setState({
         current: image
       })
      }
    
      handleCloseModal = (e) => {
       e && e.preventDefault();
    
       this.setState({
         current: ''
       })
      }
    
      render(){
       const settings = this.getSliderSettings();
       const { images, current } = this.state;
    
       return (
         <div>
          <Slider {...settings}>
            { images.map(image => (
               <img src={image} onClick={ e => this.handleClickImage(e, image)}  />
    
            ))} 
          </Slider>
    
          {current &&
             <Lightbox
                mainSrc={current}
                onCloseRequest={this.handleCloseModal}
                />
          }
        </div>
       )
      }
    }