Search code examples
reactjsantd

ant Design Carousel: how to access the goto(), next(), & prev() methods


We're using ant Design in our project and I'm trying to use their Carousel component. The documentation shows methods goto(), next(), prev() but I am unable to access these methods. The way we've done this with other antD components would be to:

const { goto, next, prev } = Carousel;

once you've imported Carousel, but this doesn't work -- those methods are all undefined. These methods were exposed in this 2017 pull request (although the original pull request references previous() instead of prev()) but I see no way to access them. This PR also mentioned that the purpose of the PR was to make the methods available without having to useRefs, which is what all the SO examples seem to show are class-based solutions, not Hooks as we are using.

What am I missing here?


Solution

  • You can create a ref and pass it to the carousel and from that you can access the carousel methods.

     const carouselRef = React.createRef();
    
     <Carousel dotPosition={dotPosition} ref={carouselRef}>
     <Button  onClick={() => {
           carouselRef.current.next();
         }}
     >
                goto next
              </Button>
      <Button
                onClick={() => {
                  carouselRef.current.prev();
                }}
              >
                goto prev
              </Button>
    </Carousel>