How to execute slickNext method in react-slick carousel?
Asked Answered
R

2

8

I have the following React app with a Slick carousel. I created a custom Next button and need to execute the slickNext() method to proceed to the next slide. The Slick carousel docs and some of the answers for questions have mentioned the following way to call slickNext() method.

The problem is I'm getting the error slider.slick is not a function.

This is what I have tried so far

gotoNext = () => {
    var slider = document.getElementsByClassName("sliderMain")[0];
    console.log("set", slider)
    slider.slick("slickNext");
}

const SampleNextArrow = (props) => {
        const { className, style } = props;
        return (
            <div
                className={className}
                onClick={this.gotoNext}
            />
           );
        }

    const settings = {
        dots: true,
        infinite: false,
        speed: 500,
        slidesToShow: 1,
        slidesToScroll: 1,
        swipe: false,
        nextArrow: <SampleNextArrow className="customSlickNext" />,
    };

    <Slider
       id="sliderMain"
       {...settings}
       className="sliderMain"
       afterChange={this.changeSlide}
    >{ /* slider goes here */}
    </Slider>

How can I solve this?

Ricercar answered 10/11, 2020 at 20:12 Comment(3)
why do you have some code after return statement?Slalom
@Saeid-a That's my custom arrow divRicercar
You may want to look in the react-slick docs instead, as the method calls are performed differently: react-slick.neostack.com/docs/apiAeropause
A
30

With react-slick, you can add a ref prop on <Slider>. If you're using hooks, you can do that with useRef():

import React, { useRef } from 'react';

...

const sliderRef = useRef();

<Slider
    ref={sliderRef}
    ...
>
</Slider>

You can then use sliderRef to call Slick methods in your function:

gotoNext = () => {
    sliderRef.current.slickNext();
}

The available methods for react-slick can be found at: https://react-slick.neostack.com/docs/api/#methods

Aeropause answered 10/11, 2020 at 23:14 Comment(1)
Thank you. I'm using a class component. So, React.createRef(); worked for meRicercar
L
3

I have solution when we have slider in one component and custom methods slickNext(), slickPrev() in other component.

we can't send ref as prop. we should use forwardRef

in react-slick, you can use forwardRef() on <Slider>.

 //carousel.js(child)
    import React, { useRef } from 'react';


    const Carousel = React.forwardRef((props, ref) => {


    <Slider
        ref={ref}
        ...
    >
    </Slider>

    })

now you can access ref in parent component

import Carousel from "./carousel";

let sliderRef = React.useRef();


<a onClick={()=>sliderRef?.current?.slickNext()}>Next</a>
<a onClick={()=>sliderRef?.current?.slickPrev()}>Prev</a>
  
  
<Carousel ref={sliderRef}></Carousel>
     
Liquidator answered 26/8, 2021 at 7:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.