5

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?

JESii
  • 4,678
  • 2
  • 39
  • 44
  • 1
    It looks like you can only access those methods via using `useRef`: https://codesandbox.io/s/serene-fire-1v576. The react-slick methods weren't elevated past the confined Carousel component, so passing in props won't work. As you can see in the Carousel component, they aren't exposed to any props: https://github.com/ant-design/ant-design/blob/master/components/carousel/index.tsx#L112-L122 – Matt Carlotta Oct 26 '19 at 15:34
  • Thanks, @MattCarlotta. The whole point of that PR I mentioned was to do just that - expose the methods...and yes, there are a number of posts with `useRef` examples; thanks for your addition which I will review. – JESii Oct 26 '19 at 17:42
  • The point of the PR was to expose the react-slick methods to the `Carousel` component so that you wouldn't have to go two levels deep. That said, calling a child's class method from a parent isn't very React-like. Instead, you'll ideally pass down a callback function (props) to the child to elevate a child's method. However, if that method isn't exposed to props, then you'll need to use refs: https://stackoverflow.com/a/37950970/7376526 – Matt Carlotta Oct 26 '19 at 18:21

2 Answers2

1

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>
Waqas Khan
  • 57
  • 8
0

if you want to use the Carousel's methods,you shoule get the instance of Carousel Component.

like this: codesandbox

LeeKlaus
  • 156
  • 8