Slideshow autoplay doesn’t work when using async slides #391
|
Hello, slideshow={{ autoplay: true }} doesn’t start automatically when slides are loaded asynchronously (e.g. from an API), but works fine when slides are already present. Code to reproduction the issue: Question: Is this expected? What’s the recommended way to make autoplay work with async slides? Thanks! |
Replies: 2 comments
|
This is expected behavior. The Here are two recommended approaches: Option 1: Render the lightbox only when slides are ready export default function Test() {
const [slides, setSlides] = useState();
useEffect(() => {
axios
.get("https://picsum.photos/v2/list?page=1&limit=3")
.then((res) =>
setSlides(res.data.map((img) => ({ src: img.download_url }))),
);
}, []);
if (!slides) {
return <div>Loading placeholder</div>;
}
return (
<div style={{ position: "fixed", inset: 0 }}>
<Lightbox
slides={slides}
plugins={[Inline, Slideshow]}
slideshow={{ autoplay: true, delay: 5000 }}
/>
</div>
);
}Option 2: Remount the lightbox with a key when slides change export default function Test() {
const [slides, setSlides] = useState([]);
const [slidesKey, setSlidesKey] = useState(0);
useEffect(() => {
axios
.get("https://picsum.photos/v2/list?page=1&limit=3")
.then((res) => {
setSlides(res.data.map((img) => ({ src: img.download_url })));
setSlidesKey((prev) => prev + 1);
});
}, []);
return (
<div style={{ position: "fixed", inset: 0 }}>
<Lightbox
key={slidesKey}
slides={slides}
plugins={[Inline, Slideshow]}
slideshow={{ autoplay: true, delay: 5000 }}
/>
</div>
);
}Option 1 is the simplest and recommended approach. For more granular control over slideshow playback, you can also use the slideshowRef — see the https://yet-another-react-lightbox.com/plugins/slideshow#SlideshowRef for details. |
|
Thanks got it! |
This is expected behavior. The
autoplayoption sets the initialplayingstate when the component mounts. When the lightbox mounts with an empty slides array,playingis immediately disabled (no slides to play), and it won't re-activate when slides arrive later.Here are two recommended approaches:
Option 1: Render the lightbox only when slides are ready