0

I have a simple section in which contains a slick slider I want on clicking a button eg button 1 it should open a specific slide.

Here is the live demo on codesandbox slick go to slide

Here is the js code

import React, { useRef, useState, useEffect } from "react";
import Slider from "react-slick";

export default function APP() {
  const sliderRef = useRef();
  const [slideIndex, setSlideIndex] = useState(0);

  var settings = {
    dots: true
  };

  useEffect(() => {
    sliderRef.current.slickGoTo(slideIndex);
  }, [slideIndex]);

  return (
    <div className="container">
      <Slider {...settings} ref={sliderRef}>
        <div>
          <img src="http://placekitten.com/g/400/200" />
          <button onClick={setSlideIndex(0)}>btn 1</button>
          <button onClick={setSlideIndex(1)}>btn 2</button>
          <button onClick={setSlideIndex(2)}>btn 3</button>
        </div>
        <div>
          <img src="http://placekitten.com/g/400/200" />
        </div>
        <div>
          <img src="http://placekitten.com/g/400/200" />
        </div>
        <div>
          <img src="http://placekitten.com/g/400/200" />
        </div>
      </Slider>
    </div>
  );
}

but I get the following error

Too many re-renders. React limits the number of renders to prevent an infinite loop

What is wrong here?

The Dead Man
  • 6,258
  • 28
  • 111
  • 193

1 Answers1

2

Your onClick props should be functions, not function calls.

So this

onClick={setSlideIndex(0)}

Should be this:

onClick={() => setSlideIndex(0)}

The way you have it now, the function is called when the component renders. And the function changes the state, which causes a re-render, which calls that function again, which triggers a state change, etc. etc. -> infinite loop

Jayce444
  • 8,725
  • 3
  • 27
  • 43
  • Read through the documentation for the `react-slick` library and look at the examples. You'll get an understanding of what you need (in this case you needed the styling, which the docs mention). Here's a basic sandbox with your code working: https://codesandbox.io/s/musing-elbakyan-e7upi?file=/src/App.js – Jayce444 Apr 28 '21 at 01:30