Fatemeh Qasemkhani
Fatemeh Qasemkhani

Reputation: 2042

Change slick slider slides from another component

I have two separate components. In component A I have some links and in the component B have an slick slider. How can I change the slides with Links onClick event in component A.

Upvotes: 3

Views: 4463

Answers (1)

Corey Larson
Corey Larson

Reputation: 1154

You need to manage a slideIndex state in the closest common parent component.

Pass down setSlideIndex as a prop for the Links component to update the state. The state is passed down to the Slider component and use react-slick's slickGoTo function to update the carousel with useEffect.

import React, { useState, useEffect, useRef } from "react";
import Carousel from "react-slick";
import "slick-carousel/slick/slick.css";

function Parent() {
  const [slideIndex, setSlideIndex] = useState(0);

  return (
    <>
      <Links onClick={setSlideIndex} />
      <Slider slideIndex={slideIndex} />
    </>
  );
}

function Links({ onClick }) {
  return (
    <ul>
      <li>
        <button onClick={() => onClick(0)}>Show Slide 1</button>
      </li>
      <li>
        <button onClick={() => onClick(1)}>Show Slide 2</button>
      </li>
      <li>
        <button onClick={() => onClick(2)}>Show Slide 3</button>
      </li>
      <li>
        <button onClick={() => onClick(3)}>Show Slide 4</button>
      </li>
    </ul>
  );
}

function Slider({ slideIndex }) {
  const slider = useRef();

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

  return (
    <Carousel ref={slider}>
      <div>Slide 1</div>
      <div>Slide 2</div>
      <div>Slide 3</div>
      <div>Slide 4</div>
    </Carousel>
  );
}
Slider.defaultProps = {
  slideIndex: 0
};

Upvotes: 7

Related Questions