[Help]: Why is slidesInView
giving multiple indices when there should only be 1 index?
#948
-
SummaryThis is very similar to this question: #943, but I still have further questions. I have an basic embla carousel on react and autoplay that only shows 1 page per slide since each slide's width is 100%. I'm trying to grab the index of currently active slide, and since 1 slide takes up the whole carousel, I expect to only get 1 index as result. But for some reason I'm getting 2 indices (and sometimes 1 or even 3) from Here I've set up a very basic embla carousel using example from embla documentation on CodeSandbox. What is it that I'm not doing right? How do I tell which slide is currently active? https://codesandbox.io/p/sandbox/festive-aj-ssxckq If applicable, which variants of Embla Carousel are relevant to this question?
Additional informationimport "./styles.css";
import { useState, useCallback, useEffect } from "react";
import useEmblaCarousel from "embla-carousel-react";
import Autoplay from "embla-carousel-autoplay";
export default function App() {
const [slides, setSlides] = useState([]);
const [emblaRef, emblaApi] = useEmblaCarousel({ loop: true }, [
Autoplay({
stopOnInteraction: false,
}),
]);
const logSlidesInView = useCallback((emblaApi) => {
console.log(emblaApi.slidesInView());
setSlides(emblaApi.slidesInView());
}, []);
useEffect(() => {
if (emblaApi) emblaApi.on("slidesInView", logSlidesInView);
}, [emblaApi, logSlidesInView]);
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<div className="embla" ref={emblaRef}>
<div className="embla__container">
<h1 className="embla__slide">Slide 0</h1>
<h1 className="embla__slide">Slide 1</h1>
<h1 className="embla__slide">Slide 2</h1>
</div>
<h1>SlidesInView: {slides.toString()}</h1>
</div>
</div>
);
}
// And the CSS
.embla {
overflow: hidden;
}
.embla__container {
display: flex;
}
.embla__slide {
flex: 0 0 100%;
min-width: 0;
padding: 100px 0;
background-color: aquamarine;
} CodeSandbox example |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Hi @dermatobia, Thanks for your question. I think you need to make your CodeSandbox public because I can’t access it.
If you want to track and watch the selected index, you can pick any carousel with dot navigation on the examples page and see how it’s done in the code there. For example, this example has dot navigation. |
Beta Was this translation helpful? Give feedback.
@dermatobia after testing your CodeSandbox, I think it has to do with fractional pixels. Embla is using the browser native Intersection Observer under the hood and the default threshold is
[0]
, which means that an element will be considered in view even if only half a pixel of it is in view.To solve this. simply increase the threshold using the Embla
inViewThreshold
option like so: