react-slick: slickGoTo inside useEffect doesn't work.

so I have following problem, I want my slider to go back to slide 6 after if anyone would try to swipe further. However it doesn’t work. UseEffect is being triggered, IF condition is being met, but the function won’t run. If I put the same function call inside JSX like first snippet below it works how it should:

<button onClick={() => sliderRef.current.slickGoTo(5)} >go to slide 6</button>

This is my code:

const [activeSlide, setActiveSlide] = useState(0)
const sliderRef = useRef(null)
  const settings = {
    variableWidth: true,
    speed: 500,
    pauseOnHover: false,
    swipeToSlide: false,
    focusOnSelect: false,
    infinite: false,
    slidesToScroll: 1,
    arrows: false,
    beforeChange: (current, next) => setActiveSlide(next)
  }
useEffect(() => {
    if (window.innerWidth > 1100 && activeSlide > 5) {
      sliderRef.current.slickGoTo(5)
    }
  }, [activeSlide])
<Slider {...settings} className={sliderClass} ref={sliderRef}>

About this issue

  • Original URL
  • State: open
  • Created 3 years ago
  • Reactions: 3
  • Comments: 20

Most upvoted comments

@ankumar3 Not sure on the cause. But for me, I have found that useRef doesn’t work and I needed to create a state reference. So, instead of:

const sliderRef = useRef(null);
...
<Slider ref={ sliderRef }>

I had to use the following:

const [ slickSlider, setSlickSlider ] = useState(null);
...
<Slider ref={ slider => setSlickSlider( slider ) }>

I found this out from this example.

What helped me: const sliderRef = useRef(null); useEffect(() => sliderRef.current?.innerSlider?.changeSlide({ message: 'index', index: 0 }, true), [])

Got that from reading react-slick code

Awesome, thanks for sharing @jaredparker

In my case, I needed to open a particular slide on Carousel Init only so I used the Slider onInit like this: const onInit = () => {setInitState(true)} ... <Slider ref={ sliderRef } onInit={onInit}>

And then used the useEffect: useEffect(() => { sliderRef.current?.slickGoTo(index) }, [initState])

Same issue here