Search code examples
javascriptreactjsreact-slick

Change Slide on Button Click - react-slick


I am using react slick in my react project. I have 5 slides, one button(Go to Slide3), and one text(Current Slide Number) in my UI.

When I click the button, in the react-slick, it should move to the third slide. Whenever the slide change, I also want to set the current slide number.
Here's the UI:

enter image description here

I tried but I don't know how to make it. I searched react-slick documentation but unable to find that how to change the slide on the outer button click. In Documentation, it shows functions for prev and next arrow click

Here's the Code SandBox Link:
https://codesandbox.io/s/react-slick-custom-arrows-and-dots-example-forked-1hq26c?file=/src/App.js


Solution

  • You can use slickGoTo method.

    This method accepts index, where you want to slide!

    First, you have to create ref and pass it to the react-slick component, then you can access the methods provided by react-slick.

    https://react-slick.neostack.com/docs/api/#methods

    Here is the example:

    
    import React, { useRef } from "react";
    import "./styles.css";
    
    import "slick-carousel/slick/slick.css";
    import "slick-carousel/slick/slick-theme.css";
    
    import Slider, { slickGoTo } from "react-slick";
    import { useState } from "react";
    
    function Arrow(props) {
      let className = props.type === "next" ? "nextArrow" : "prevArrow";
      className += " arrow";
      const char = props.type === "next" ? "👉" : "👈";
      return (
        <span className={className} onClick={props.onClick}>
          {char}
        </span>
      );
    }
    
    export default function App() {
      const sliderRef = useRef();
    
      const [currentSlide, setCurrentSlide] = useState("Slide 1");
      const slides = ["Slide 1", "Slide 2", "Slide 3", "Slide 4", "Slide 5"];
      const renderSlides = () =>
        slides.map((text) => (
          <div>
            <h3>{text}</h3>
          </div>
        ));
    
      return (
        <div className="App">
          <Slider
            nextArrow={<Arrow type="next" />}
            prevArrow={<Arrow type="prev" />}
            ref={sliderRef}
          >
            {renderSlides()}
          </Slider>
    
          <button
            style={{ marginTop: "10px" }}
            onClick={() => {
              setCurrentSlide("Slide 3");
              //Indexing starts from 0
              sliderRef.current.slickGoTo(2);
            }}
          >
            Goto Slide 3
          </button>
          <div style={{ marginTop: "10px" }}>Current Slide : {currentSlide} </div>
        </div>
      );
    }
    
    

    Thanks!