Have you met Swiper.js? It’s a really good slider/carousel for the web.
However, for React developers, a new version (^11) of Swiper is going to drop support for React components.
Swiper React components will likely be removed in future versions. It is recommended to migrate to Swiper Element instead.
Swiper React Documentation
Swiper Element supports web components, but React (18).. partially too.
Documentation for React developers is a bit poor, so take a look at the following example of how to use the new Swiper with Next.js and custom Navigation.
'use client'; // slider have a couple of interactions with user so `use client`
import { useEffect, useRef } from 'react';
// import swiper
import 'swiper/css';
import { register } from 'swiper/element/bundle';
import { A11y } from 'swiper/modules';
import styles from './Slider.module.scss';
import Button from '../Button/Button';
interface SliderProps {
slides: {
title: string;
text: string;
link: string;
}[];
}
// start here and register swiper
register();
export default ({ slides }: SliderProps) => {
const swiperElRef = useRef<any>(null); // create ref
useEffect(() => {
if (swiperElRef.current) {
// add your own config for slider
const params = {
autoHeight: true,
modules: [A11y],
};
Object.assign(swiperElRef.current, params);
swiperElRef.current.initialize();
}
}, []);
// custom handler for next/prev events
const nextSlide = () => {
swiperElRef.current?.swiper.slideNext(200);
};
const prevSlide = () => {
swiperElRef.current?.swiper.slidePrev(200);
};
return (
<div className={styles.sliderWrapper}>
<div className={styles.sliderInner}>
<swiper-container ref={swiperElRef}>
{slides.map((slide, i) => (
<>
<swiper-slide key={`el_${i}`}>
<div className={styles.slide}>Slide {slide.title}</div>
</swiper-slide>
</>
))}
</swiper-container>
<Button
color="black"
className={styles.prevBtn}
onClick={() => prevSlide()}
icon="arrow-left"
/>
<Button
color="black"
className={styles.nextBtn}
onClick={() => nextSlide()}
icon="arrow"
/>
</div>
</div>
);
};
Your TypeScript might throw an error stating:
Property 'swiper-container' does not exist on type 'JSX.IntrinsicElements'.ts(2339)
To resolve this, add the following declaration to your global types file in the main directory.
declare global {
namespace JSX {
interface IntrinsicElements {
'swiper-container': React.DetailedHTMLProps<
React.HTMLAttributes<HTMLElement>,
HTMLElement
>;
'swiper-slide': React.DetailedHTMLProps<
React.HTMLAttributes<HTMLElement>,
HTMLElement
>;
}
}
}
export default global;
Now you should be able to use Swiperjs in your React or Nextjs with the latest version.
Leave a Reply
You must be logged in to post a comment.