Using Swiper Element In React

Jul 3, 2023

Updated on July 28 2023 - added Virtual Slides implementation

Let's take a bit closer look on how to use the Swiper web component in React.

Parameters

React doesn't support custom elements (web components) natively yet, so this code:

<swiper-container
  slides-per-view={3}
  breakpoints={{
    768: {
      slidesPerView: 4,
    },
  }}
>
  ...
</swiper-container>

actually renders to the following:

<swiper-container slides-per-view="3" breakpoints="[object Object]">
  ...
</swiper-container>

which is not what we expect.

This is why it is required to use Swiper Element in React by passing parameters as props and use custom initialization:

import { useEffect, useRef } from 'react';
import { register } from 'swiper/element/bundle';

export default function App() {
  const swiperRef = useRef(null);

  useEffect(() => {
    // Register Swiper web component
    register();

    // Object with parameters
    const params = {
      slidesPerView: 3,
      breakpoints: {
        768: {
          slidesPerView: 4,
        },
      },
    };

    // Assign it to swiper element
    Object.assign(swiperRef.current, params);

    // initialize swiper
    swiperRef.current.initialize();
  }, []);

  return (
    <swiper-container init="false" ref={swiperRef}>
      ...
    </swiper-container>
  );
}

Events

Same with events, they can not be assigned using React's on[Event] syntax and should be added using .addEventListener method or by passing them in on in parameters:

import { useEffect, useRef } from 'react';
import { register } from 'swiper/element/bundle';

export default function App() {
  const swiperRef = useRef(null);

  useEffect(() => {
    // Register Swiper web component
    register();

    // Add event listener
    swiperRef.current.addEventListener('swiperslidechange', (e) => {
      console.log(e.detail);
    });

    // Object with parameters
    const params = {
      // or pass it in on
      on: {
        slideChange(s) {
          console.log(s);
        },
      },
    };

    // Assign it to swiper element
    Object.assign(swiperRef.current, params);

    // initialize swiper
    swiperRef.current.initialize();
  }, []);

  return (
    <swiper-container init="false" ref={swiperRef}>
      ...
    </swiper-container>
  );
}

Custom Wrapper Component

If you have a lot of Swipers in your project, we can make a simple React component that basically wraps a Swiper Element:

import { useEffect, useRef } from 'react';
import { register } from 'swiper/element/bundle';

export function Swiper(props) {
  const swiperRef = useRef(null);
  const {
    children,
    ...rest
  } = props;

  useEffect(() => {
    // Register Swiper web component
    register();

    // pass component props to parameters
    const params = {
      ...rest
    };

    // Assign it to swiper element
    Object.assign(swiperRef.current, params);

    // initialize swiper
    swiperRef.current.initialize();
  }, []);

  return (
    <swiper-container init="false" ref={swiperRef}>
      {children}
    </swiper-container>
  );
}
export function SwiperSlide(props) {
  const {
    children,
    ...rest
  } = props;

  return (
    <swiper-slide {...rest}>
      {children}
    </swiper-slide>
  );
}

And now we can use it in the following way across our app:

import { Swiper, SwiperSlide } from 'path/to/my-swiper.jsx';

export default function App() {
  return (
    <Swiper
      slidesPerView={3}
      breakpoints={{ 768: { slidesPerView: 4 } }}
      on={{
        slideChange: () => console.log('slide changed'),
        progress: (s, progress) => console.log(`progress is ${progress}`),
      }}
    >
      <SwiperSlide>Slide 1</SwiperSlide>
      <SwiperSlide>Slide 2</SwiperSlide>
      <SwiperSlide>Slide 3</SwiperSlide>
    </Swiper>
  );
}

Virtual Slides

If you use Virtual Slides, we can go deeper and implement virtual slides in React-way too. We need to modify Swiper component a bit in the following way:

import React, { useEffect, useState, useRef } from 'react';
import { register } from 'swiper/element/bundle';

export function Swiper(props) {
  const swiperRef = useRef(null);
  const {
    children,
    virtual, // specify virtual prop
    ...rest
  } = props;

  // store virtual data
  const [virtualData, setVirtualData] = useState({
    from: 0,
    to: 0,
    offset: 0,
    slides: [],
  });

  useEffect(() => {
    // Register Swiper web component
    register();

    // pass component props to parameters
    const params = {
      ...rest
    };

    // if we have virtual prop passed add virtual prameters
    if (virtual) {
      params.virtual = {
        enabled: true,
        // pass component children (slides) in `slides` array
        slides: children,
        // set virtual data on renderExternal
        renderExternal(vd) {
          setVirtualData(vd);
        },
      };
    }

    // Assign it to swiper element
    Object.assign(swiperRef.current, params);

    // initialize swiper
    swiperRef.current.initialize();
  }, []);

  // calc slides to render
  const slides = virtual
    ? virtualData.slides.map((slide, index) =>
        // clone slide
        React.cloneElement(slide, {
          // add key
          key: virtualData.from + index,
          // set slides offset
          style: {
            [props.direction === "vertical" ? "top" : "left"]:
              virtualData.offset,
          },
          // add and swiper slide index to data attribute
          ["data-swiper-slide-index"]: virtualData.from + index,
        })
      )
    : children; // return children if virtual is disabled

  return (
    <swiper-container init="false" ref={swiperRef}>
      {slides}
    </swiper-container>
  );
}

// SwiperSlide component stays the same
export function SwiperSlide(props) {
  const {
    children,
    ...rest
  } = props;

  return (
    <swiper-slide {...rest}>
      {children}
    </swiper-slide>
  );
}

And now we can easily create Swiper with virtual slides in React:

import { Swiper, SwiperSlide } from 'path/to/my-swiper.jsx';

export default function App() {
  return (
    <Swiper virtual navigation>
      <SwiperSlide>Slide 1</SwiperSlide>
      <SwiperSlide>Slide 2</SwiperSlide>
      <SwiperSlide>Slide 3</SwiperSlide>
      ...
      <SwiperSlide>Slide 1000</SwiperSlide>
    </Swiper>
  );
}

P.S.

And as always, if you love Swiper, please, support project by donating or pledging:

And checking our premium projects:

Your support means a lot for us!