Is there a way to customize yet-another-react-lightbox carousel for a rotating display (autoplay)?

737 Views Asked by At

I'm using next@13 and trying to make the inline carousel of yet-another-react-lightbox(v3.12.2) to navigate every few seconds.

This is what I tried :

'use client';

import Lightbox, { useController } from 'yet-another-react-lightbox';
import Inline from 'yet-another-react-lightbox/plugins/inline';

export default function MyComponent ({ slides }: Props) {
  const { next } = useController();

  useEffect(() => {
      setTimeout(function () {
        next();
      }, 3000);
    });

    return (
      <Lightbox
        slides={slides}
        plugins={[Inline]}
        inline={{
          style: {...},
        }}
        carousel={{...}}
      />
    );
}

But it doesn't work, I'm getting this error :

Error: useController must be used within a ControllerContext.Provider

I don't see what would be a context with this useController() hook inside. Maybe it is a "props augmentation that needs to be done, but I don't understand very well the documentation about it. Has anyone an idea ? Thanks !!

1

There are 1 best solutions below

0
Igor Danchenko On

useController and other internal lightbox hooks can only be used in a component rendered inside the lightbox (i.e., in a component rendered through a custom render function, or in a component added to the lightbox with a plugin)

https://yet-another-react-lightbox.com/advanced#Hooks

But since in this case you want to use the lightbox controller outside the lightbox component, you need to use a ref to access the controller.

export default function MyComponent({ slides }: Props) {
  const ref = React.useRef<ControllerRef>(null);

  React.useEffect(() => {
    let mounted = true;

    setTimeout(() => {
      if (mounted) {
        ref.current?.next();
      }
    }, 3000);

    return () => {
      mounted = false;
    };
  });

  return (
    <Lightbox
      slides={slides}
      plugins={[Inline]}
      controller={{ ref }}
      inline={{ style: { ... } }}
    />
  );
}

You may also want to take a look at the Slideshow plugin as it sounds like that's what you are trying to implement - https://yet-another-react-lightbox.com/plugins/slideshow