yaodingyd / react-flickity-component

A React.js component for using @desandro's Flickity
314 stars 51 forks source link

How to perform an onChange event #85

Closed guille-alibrate closed 4 years ago

guille-alibrate commented 4 years ago

I'm trying to get the current index of the slides. So, my first attempt is using something like "onChange". But I see it's not supported in the Props interface:

interface Props {
    className?: string;
    disableImagesLoaded?: boolean;
    elementType?: string;
    flickityRef?: (ref: Flickity) => void;
    options?: FlickityOptions;
    reloadOnUpdate?: boolean;
    static?: boolean;
}

I tried passing the event an an option, with no luck:

const flickityOptions = {
    contain: true,
    pageDots: false,
    cellAlign: 'left',
    onChange: (i) => console.log('index', i)
  }

Any clue?

guille-alibrate commented 4 years ago

Sorry, it's in the docs. I mean, I can get a ref and then get the index. https://github.com/theolampert/react-flickity-component#use-flickitys-api-and-events

Doc shows how to do it with class component. For functional, this works:

const Carousel = React.forwardRef(({ children }, externalRef) => {
  return (
    <Flickity
      flickityRef={(carouselRef) => { if (externalRef) externalRef.current = carouselRef }}
    >
      {children}
    </Flickity>
  )
})

Then you call it like:

const carouselRef = useRef(null)
...
<Carousel ref={carouselRef}>
    ...
</Carousel>
yaodingyd commented 4 years ago

Can I close the issue since you have figured it out?

guille-alibrate commented 4 years ago

Sure. Let's close it.

alanoakden commented 3 years ago

Sorry, it's in the docs. I mean, I can get a ref and then get the index. https://github.com/theolampert/react-flickity-component#use-flickitys-api-and-events

Doc shows how to do it with class component. For functional, this works:

const Carousel = React.forwardRef(({ children }, externalRef) => {
  return (
    <Flickity
      flickityRef={(carouselRef) => { if (externalRef) externalRef.current = carouselRef }}
    >
      {children}
    </Flickity>
  )
})

Then you call it like:

const carouselRef = useRef(null)
...
<Carousel ref={carouselRef}>
    ...
</Carousel>

Sorry I am struggling to put together the final part, I have all that in place and the ref is working, but how do I use it with an onChange listener or similar ?