1

How can I detect if the user has clicked the previous/next arrow to toggle the value of the autoplay in react-multi-carousel?

 return (
    <Carousel
      autoPlay={true}
      autoPlaySpeed={4500}
      customTransition="all .5"
      transitionDuration={300}
      infinite={true}
    
    >
      {movies.map((movie) => (
        <img
          key={movie.id}
          style={{ width: "100%", height: "100%" }}
          src={movie.image}
          alt={movie.title}
        />
      ))}
    </Carousel>
Pep
  • 647
  • 6
  • 20

2 Answers2

2

If you're curious about anything called when the page switches,

When you see the documentation for that 'react-multi-carousel', There is a callback fuction called when a page is converted.

here

<Carousel
  afterChange={(previousSlide, { currentSlide, onMove }) => {
    doSpeicalThing();
  }}
  beforeChange={(nextSlide, { currentSlide, onMove }) => {
    doSpeicalThing();
  }}
/>
Changhoon Lee
  • 143
  • 2
  • 14
  • I want to specifically detect the click @Changhoon Lee – Pep Dec 09 '20 at 02:03
  • Please explain the specific actions you want to obtain by clicking. When clicked, the slider will only move, and then the function I suggested will work. You can add the function you want to it. Or looking for other interactions? @Pep – Changhoon Lee Dec 09 '20 at 06:57
1

As Changoon Lee mentioned in their answer, you can use the beforeChange and afterChange callbacks which are invoked each time before and after a sliding.

If you only want to detect button clicks (and not keyboard slides or drags), you can create new button components and pass them as custom arrows. Your custom buttons will receive a list of props/state; one of them is the react-multi-carousel's onClick handler.

You can pass your custom buttons to the Carousel as props (customLeftArrow and customRightArrow).

function CustomRightArrow({ onClick }) {
  function handleClick() {
    // do whatever you want on the right button click
    console.log('Right button clicked, go to next slide');
    // ... and don't forget to call onClick to slide
    onClick();
  }

  return (
    <button
      onClick={handleClick}
      aria-label="Go to next slide"
      className="react-multiple-carousel__arrow react-multiple-carousel__arrow--right"
    />
  );
}

function App() {
  return (
    <Carousel
      customLeftArrow={<CustomLeftArrow />}
      customRightArrow={<CustomRightArrow />}
      infinite
      keyBoardControl
    >
      {images.map((image, i) => {
        return (
          <img
            key={i}
            style={{ width: '100%', height: '100%' }}
            src={image}
            alt=""
          />
        );
      })}
    </Carousel>
  );
}
Zsolt Meszaros
  • 21,961
  • 19
  • 54
  • 57