React Spring Carousel

Fullscreen

For me, this is an essential feature that I've hardly found easy to use (when implemented 😒) in other libraries. Well, React Spring Carousel, of course, make it easy for you - thanks to screenfull library.


  import { useSpringCarousel } from 'react-spring-carousel'

  export function Component() {
    const { 
      carouselFragment,
      slideToPrevItem,
      slideToNextItem,
      enterFullscreen,
    } = useSpringCarousel({
      items: (
        <CarouselItem color={i.color}>
          {i.title}
        </CarouselItem>
      ),
    });

    return (
      <div>
        <button onClick={slideToPrevItem}>Prev item</button>
        {carouselFragment}
        <button onClick={slideToNextItem}>Next item</button>
      </div>
    );
  }

As you may see, entering just the carousel viewport in fullscreen (the default behavior) could be useful, but sometimes you'll want to throw all your carousel components into the fullscreen world. Well, that's an easy task too 😼

For completeness, and to make the example clear, the following snippet will contain all the rendering items that I'll use in the site (my custom Playground).

  import { useSpringCarousel } from 'react-spring-carousel'

  function Component(){
    const {
      carouselFragment,
      slideToPrevItem,
      slideToNextItem,
      enterFullscreen // -> All for one,
      exitFullscreen // -> and
      getIsFullscreen // -> one for all 
    } = useSpringCarousel({
      items: mockedItems.map((i) => ({
        id: i.id,
        renderItem: <CarouselItem color={i.color}>{i.title}</CarouselItem>,
      })),
    });
    // Create a react ref
    const ref = useRef<HTMLDivElement | null>(null);

    return (
      <Playground
        // Assign the ref
        ref={ref}
        slideToPrevItem={slideToPrevItem}
        slideToNextItem={slideToNextItem}
        customControls={
          <Button
            onClick={() => {
              if (getIsFullscreen()) {
                exitFullscreen();
              } else {
                // Pass the ref!
                enterFullscreen(ref.current);
              }
            }}
          >
            Toggle fullscreen!
          </Button>
        }
      >
        {carouselFragment}
      </Playground>
  }

As you can see, building a toggle fullscreen button is easy as a piece of cake! 🥮