Home > Blockchain >  Splide js React how to specify certain slide by clicking static thumbnails using '.go()'
Splide js React how to specify certain slide by clicking static thumbnails using '.go()'

Time:06-11

I am coding with React (FC not class) and Splide js to make carousel and thumbnails. Thumbnails should not be a carousel, should be static and like bottons.

I read the official document and could not redo on React. I am using 'useRef' hook but I don't know how to connect with .go() function. Here is my code:

Hero.tsx

import { Splide, SplideSlide } from '@splidejs/react-splide';
import { Options } from '@splidejs/splide';

import '@splidejs/react-splide/css';

import './Hero.scss';

import p1 from '../assets/image-product-1.jpg';
import p2 from '../assets/image-product-2.jpg';
import p3 from '../assets/image-product-3.jpg';
import p4 from '../assets/image-product-4.jpg';

import { useRef } from 'react';

export default function Hero() {
  const thumbsImages = [
    require('../assets/image-product-1-thumbnail.jpg'),
    require('../assets/image-product-2-thumbnail.jpg'),
    require('../assets/image-product-3-thumbnail.jpg'),
    require('../assets/image-product-4-thumbnail.jpg'),
  ];

  const mainOptions: Options = {
    type: 'loop',
    perPage: 1,
    perMove: 1,
    gap: '1rem',
    pagination: false,
    height: '27.8125rem',
  };

  const mainRef = useRef<Splide>(null);

  const handleThumbs = (id: number) => {
    mainRef.go(id);
  };

  return (
    <>
      <Splide options={mainOptions} ref={mainRef}>
        <SplideSlide>
          <img src={p1} alt="product image 1" />
        </SplideSlide>
        <SplideSlide>
          <img src={p2} alt="product image 2" />
        </SplideSlide>
        <SplideSlide>
          <img src={p3} alt="product image 3" />
        </SplideSlide>
        <SplideSlide>
          <img src={p4} alt="product image 4" />
        </SplideSlide>
      </Splide>

      <ul className="thumbnails">
        {thumbsImages.map((thumbnail, index) => (
          <li>
            <button onClick={() => handleThumbs(index)}>
              <img src={thumbnail} alt="product thumbnail" />
            </button>
          </li>
        ))}
      </ul>
    </>
  );
}

TypeScript yells at me saying Property 'go' does not exist on type 'RefObject<Splide>'.. I would like to fire the onClick function once I click each thumbnails and go to the specific slide that has the same index as the thumbnail.

I appreciate if someone could help me out.

CodePudding user response:

you have to call the go() function on the ref.current so your

handleThumb

should be

const handleThumbs = (id: number) => { mainRef.current.go(id); };

  • Related