Skip to content

useSnapNavigation

Edit on GitHub
@volvo-cars/react-headless v0.27.2

Returns prev/next button props for scroll-snap containers like carousels and reels.

import { useRef } from 'react';
import { useSnapNavigation } from '@volvo-cars/react-headless';
function Carousel() {
const ref = useRef<HTMLDivElement>(null);
const { previousButtonProps, nextButtonProps } = useSnapNavigation({ ref });
return (
<div>
<div ref={ref} className="reel gap-x-gridded-element">
<div className="snap-start shape-default bg-secondary p-24">
Slide 1
</div>
<div className="snap-start shape-default bg-secondary p-24">
Slide 2
</div>
<div className="snap-start shape-default bg-secondary p-24">
Slide 3
</div>
</div>
<button {...previousButtonProps}>Previous</button>
<button {...nextButtonProps}>Next</button>
</div>
);
}

The returned props include:

  • onClick – scrolls to the previous/next snap point
  • disabled – true when at the start/end of the container
  • aria-label and aria-hidden – the buttons are hidden from assistive technology since the scroll container is already keyboard-navigable
const { previousButtonProps, nextButtonProps } = useSnapNavigation({ ref });
// previousButtonProps.disabled is true when scrolled to the start
// nextButtonProps.disabled is true when scrolled to the end

Pair with useSnapIndicators for a complete carousel:

import { useRef } from 'react';
import {
useSnapIndicators,
useSnapNavigation,
} from '@volvo-cars/react-headless';
function FullCarousel() {
const ref = useRef<HTMLDivElement>(null);
const { indicators, activeIndex } = useSnapIndicators({ ref });
const { previousButtonProps, nextButtonProps } = useSnapNavigation({ ref });
return (
<div>
<div ref={ref} className="reel">
{/* slides */}
</div>
<div className="flex items-center gap-8">
<button {...previousButtonProps}>Previous</button>
<span>
{activeIndex + 1} / {indicators.length}
</span>
<button {...nextButtonProps}>Next</button>
</div>
</div>
);
}

useSnapNavigation accepts an options object with a ref to the scroll-snap container.

Returns:

  • previousButtonProps – props to spread on the previous button (onClick, disabled, aria-label, aria-hidden)
  • nextButtonProps – props to spread on the next button (onClick, disabled, aria-label, aria-hidden)