How to access slideToIndex(index) in react-image-gallery?

Viewed 1541

I want to create a custom control for react-image-gallery by renderCustomControls. I would like to able to access slideToIndex(). The documentation said that there is access to slideToIndex by ref. Does anyone know how to do that? Here is an example on repl.it https://repl.it/@Pyot/react-image-gallery-custom-controls

import React from 'react';
import ImageGallery from "react-image-gallery";
import './App.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/',
  },
  {
    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/',
  },
  {
    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/',
  },
];

const renderCustomControls = () => {

  const slideToIndex = (index) => null

  return <div className="custom-control">
          <div className="slider">
            <div className="bullet-left" onClick={slideToIndex(1)}></div>
          <div className="bullet" onClick={slideToIndex(5)}></div>
          <div className="bullet" onClick={slideToIndex(6)}></div>
          <div className="bullet" onClick={slideToIndex(7)}></div>
          <div className="bullet" onClick={slideToIndex(8)}></div>
          <div className="bullet-right" onClick={slideToIndex(10)}></div>
          </div>
        </div>
}

function App() {
  return (
    <div className="App">
    <ImageGallery
      renderCustomControls={renderCustomControls}
      items={images} />

    </div>
  );
}

export default App;
1 Answers

Solution: create ref and apply it on ImageGallery component.

export default function ImageGallery(props: Props) {

      const refImg = useRef(null)

      const renderCustomControls = () => <span>refImg.current.getCurrentIndex()</span>

      return (
           <ImageGallery
            ref={refImg}
            renderCustomControls={renderCustomControls}
            items={images}
          />
      )
    }
Related