DEV Community

Cover image for Build A Reusable Carousel With React And Splide.js
Femi Akinyemi
Femi Akinyemi

Posted on

Build A Reusable Carousel With React And Splide.js

In today's rapidly evolving web development landscape, the importance of creating reusable components cannot be overstated. These components play a vital role in enhancing efficiency and ensuring maintainability. Carousels are a popular choice among the widely utilized components in web design. A carousel enables users to navigate seamlessly through a collection of images or items in a sliding manner.

Thumbnail Carousel

In this article, you will build a reusable carousel component using React and Splide.Js — a lightweight and versatile slider library.

By following a systematic approach, you will cover the installation of necessary dependencies and the implementation of fundamental functionalities. Upon concluding this article, you will comprehensively understand crafting a fully functional and reusable carousel component with React and Splide.js.

This accomplishment will equip you to integrate the carousel into your future web projects effortlessly.

Why Splide?

Splide.js is a lightweight, flexible, and accessible slider and carousel library for creating web-based sliders and carousels.

It’s written in TypeScript and supports various features, such as:

  • Autoplay with a progress bar and a play-pause toggle button
  • Multiple slides
  • Slide or fade transition by CSS
  • Flexible and extensible
  • Protected by 400+ test cases
  • Lightweight, 29kB (12kB gzipped)
  • No dependencies

And many others.

Splide installation

To install Splide into your project, you can choose one of the four options listed below:

  • NPM

It is recommended to install Splide using NPM. To install the latest version, use the following command to do so:

npm install @splidejs/splide
Enter fullscreen mode Exit fullscreen mode
  • Hosting Files

You can download the Splide package from the following link:
Download

Then, Go to the dist/js directory, and import the splide.min.js file by the <script> tag:

<script src="path-to-the-file/splide.min.js"></script>
Enter fullscreen mode Exit fullscreen mode
  • CDN

You can also include this library from CDN:

jsDelivr

It is recommended to use a specific version number instead of the "latest" keyword for production to avoid unexpected breakage from the further update.

  • Integration

Integration packages are available for React, Vue and Svelte.

React Splide
Vue Splide
Svelte Splide

Integrating Splide with React

To Integrate Splide with React, you will use the recommended installation method, NPM, to install React Splide, a React component for a Splide slider/carousel.

Installation

First, you must create a React.js starter project by navigating to your desired directory and running the command below in your terminal.

npx create-react-app splidereacttutorial && cd splidereacttutorial
Enter fullscreen mode Exit fullscreen mode

The command creates a React.js project called splidereacttutorial and navigates into the project directory.

Next, you need to Install Splide by running the following command in your terminal:

$ npm install @splidejs/splide
Enter fullscreen mode Exit fullscreen mode

Usage

In the src directory, create a folder with the name components. The directory will contain all the reusable components for the carousel.

Carousel Component

In the src directory, create the file src/components/Carousel and add the following code:

import React from "react";
import { Splide, SplideSlide } from "@splidejs/react-splide";
import "@splidejs/react-splide/css";

function Carousel({ props }) {
  return (
    <div
      style={{
        display: "flex",
        justifyContent: "center",
        alignItems: "center",
      }}
    >
      <Splide
        aria-label="My Favorite Images"
        style={{
          display: "flex",
          justifyContent: "center",
          alignItems: "center",
        }}
        options={{
          width: "50%",
        }}
      >
        <SplideSlide>
          <img src={props.img_one} alt={props.img_alt} style={props.style} />
        </SplideSlide>
        <SplideSlide>
          <img src={props.img_two} alt={props.img_alt} style={props.style} />
        </SplideSlide>
      </Splide>
    </div>
  );
}

export default Carousel;

Enter fullscreen mode Exit fullscreen mode

The code above implements a React functional component called Carousel. It uses the Splide and SplideSlide components from the @splidejs/react-splide library to render a carousel with two slides that contain images. The component accepts image URLs, alternate text, and styling as props and displays the images within the carousel.

Also, In the src/App.css file, replace the code with the following code:

.App {
  display: flex;
  justify-content: center;
  align-items: center;
}
Enter fullscreen mode Exit fullscreen mode

The code above uses CSS to style the .App class, making it a flex container that horizontally and vertically centers its child elements.

Now, n the src/App.js replace the code with the following code:


import "./App.css";
import Carousel from "./components/Carousel";

function App() {

const props = {

  img_one: 'https://images.creativefabrica.com/products/previews/2023/05/11/zZEZKFvQo/2Pdr8is8AS0vymhPaFPB1WOZ7DF-desktop.jpg',
  img_two: 'https://iso.500px.com/wp-content/uploads/2016/03/stock-photo-142984111-1500x1000.jpg',
  img_alt: 'image_alt',
  style: {
    width: "100%",
    height: "400px",
    objectFit: 'cover',


  }
}

  return (
    <>
      <h1
        style={{
          textAlign: "center",
        }}
      >
        Basic Carousel
      </h1>

      <div className="App">
        <Carousel props={props} />
      </div>
    </>
  );
}

export default App;

Enter fullscreen mode Exit fullscreen mode

The code above imports a CSS file named App.css and a component called Carousel from ./components/Carousel.
Inside the App function component, an object named props is defined, which contains properties for two images (img_one and img_two), an alternate text for the images (img_alt), and styling information.

The component returns JSX elements, including a <h1> heading with the text Basic Carousel centered using inline styles.
Within an <div> element with the class App, the Carousel component is rendered with the props object passed as a prop.

Testing the Carousel component

To test the Carousel component, Navigate into your splidereacttutorial directory and run:

npm start
Enter fullscreen mode Exit fullscreen mode

Your Carousel component is now running at localhost:3000
To view the Carousel, visit localhost:3000 in your browser. You should see the component rendered.

Basic Carousel Component

Creating Auto-scroll Carousel

To create an auto-scroll carousel, you will use The Auto Scroll extension that continuously scrolls the carousel, which goes well with "Drag Free" mode.

To Install The Auto Scroll extension, run the command below in your terminal:

npm install @splidejs/splide-extension-auto-scroll
Enter fullscreen mode Exit fullscreen mode

Now, In the src/components/Carousel file, Replace the code with the following code:

import React from "react";
import { Splide, SplideSlide } from "@splidejs/react-splide";
import { AutoScroll } from "@splidejs/splide-extension-auto-scroll";
import "@splidejs/react-splide/css";

function Carousel({ props }) {
  return (
    <div>
      <Splide

        // ...

        options={{
          width: "100%",
          rewind: true,
          autoplay: "true",
          perPage: 2,
          perMove: "1",
          gap: "2rem",
          height: "15rem",
          type: "loop",
          rewindSpeed: "3000",
          arrows: "true",
          pagination: "false",
          extensions: { AutoScroll },
          autoScroll: {
            speed: 3,
            pauseOnHover: true,
            pauseOnFocus: false,
          },
          breakpoints: {
            1000: {
              perPage: 1,
            },
          },
        }}

        // ...

      >

        {/* ... */}

      </Splide>
    </div>
  );
}

export default Carousel;

Enter fullscreen mode Exit fullscreen mode

The code above sets various options for the Splide carousel component. It configures properties such as width, rewind behavior, autoplay, slide count, spacing, height, looping, rewind speed, navigation arrows, pagination, extensions, auto-scrolling behavior, and responsive breakpoints. These options define the carousel's appearance, behavior, and responsiveness.

To test the Auto Scroll extension, visit localhost:3000 in your browser. You should see the component rendered below the Basic Carousel.

Auto Scroll

Creating a Thumbnail Carousel

To create a Thumbnail Carousel, In the src directory, create a file with the name Thumbnail.js and paste the following code:

import "../App.css";
import { Splide, SplideSlide } from "@splidejs/react-splide";
import "@splidejs/react-splide/css";
import p1 from "./firstimage.jpeg";
import p2 from "./secondimage.jpeg";
import p3 from './thirdimage.jpeg';
import p4 from './fourthimage.jpeg'
import { useRef } from "react";

export default function Thumbnail() {
  const thumbsImages = [p1, p2, p3, p4];

  const mainOptions = {
    type: "loop",
    perPage: 1,
    perMove: 1,
    gap: "1rem",
    pagination: false,
    height: "27.8125rem",
  };

  const style = {
    width: "100%",
    height: "400px",
    objectFit: "cover",
  };

  const generalStyle = {
    margin: '0 auto',
    width: '50%'
  }

  const btn_img = {
      width: "70px",
      height: "70px",
      overflow: "hidden",
      listStyle: "none",
      margin: "0 0.2rem",
      cursor: "pointer"
  }

const thumbnailsstyle = {
  display: "flex",
  justifyContent: "center",
  alignItems: "center",
  listStyle: "none"
}

  const mainRef = useRef(null);

  const handleThumbs = (id) => {
    if (mainRef.current) {
      mainRef.current.go(id);
    }
  };

  return (
    <>
      <div className="App_" style={generalStyle}  >
        <div>
          <Splide options={mainOptions} ref={mainRef} style={{}}>
            <SplideSlide>
              <img src={p1} alt="product imag 1" style={style} />
            </SplideSlide>
            <SplideSlide>
              <img src={p2} alt="product imag 2" style={style} />
            </SplideSlide>

            <SplideSlide>
              <img src={p3} alt="product imag 2" style={style} />
            </SplideSlide>

            <SplideSlide>
              <img src={p4} alt="product imag 2" style={style} />
            </SplideSlide>
          </Splide>

          <ul style={thumbnailsstyle } >
            {thumbsImages?.map((thumbnail, index) => (
              <li key={thumbnail}>
                <button onClick={() => handleThumbs(index)}>
                  <img
                    src={thumbnail}
                    alt="product thumbnail"
                    style={btn_img}
                  />
                </button>
              </li>
            ))}
          </ul>
        </div>
      </div>
    </>
  );
}

Enter fullscreen mode Exit fullscreen mode

The code above is a React component that displays a main image carousel/slider and thumbnail images. It uses the Splide component from @splidejs/react-splide to create the carousel and handles thumbnail clicks to update the main carousel. The component defines image paths, carousel options, and styling objects. It renders the main carousel and thumbnail buttons using the map function.

Now, In the src/App.js file, Replace the code with the following code:

import "./App.css";
import Thumbnail from "./components/Thumbnail";

function App() {

  return (
    <>
      <h1
        style={{
          textAlign: "center",
        }}
      >
        Thumbnail Carousel
      </h1>
      <div className="App">
        <Thumbnail />
      </div>
    </>
  );
}

export default App;

Enter fullscreen mode Exit fullscreen mode

This code above is a component that serves as the application's main entry point. It imports the Thumbnail component and the App.css file for styling.

Inside the App component, it renders a heading with the text Thumbnail Carousel centered using inline styling. It also renders a <div> with the class name App and includes the Thumbnail component.

To test the Thumbnail Carousel, visit localhost:3000 in your browser.

Thumbnail Carousel

Creating a Video Carousel

To create the Video Carousel, you will use The Video extension

To Install The Video Carousel extension, run the command below in your terminal:

npm install @splidejs/splide-extension-video

Enter fullscreen mode Exit fullscreen mode

Now, In the src directory, create a file with the name VideoCarousel.js and paste the following code:


import React, { useRef } from "react";
import { Splide, SplideSlide } from "@splidejs/react-splide";
import { Video } from "@splidejs/splide-extension-video";
import "@splidejs/splide-extension-video/dist/css/splide-extension-video.min.css";

const VideoCarousel = () => {
  const options = {
    rewind: true,
    autoPlay: true,
    perPage: 2,
    gap: 10,
  };

  const videos = ["iRmx-btWrFk", "liJVSwOiiwg", "hAAZx5fHMZY"];

  const slideImageStyle = {
    maxWidth: "100%",
    height: "auto",
  };

  const mainRef = useRef(null);

  return (
    <div>
      <Splide options={options} extensions={Video} ref={mainRef}>
        {videos.map((id, index) => (
          <SplideSlide key={id} data-splide-youtube={id}>
            <iframe
              style={slideImageStyle}
              width="900"
              title={`YouTube Sample ${index + 1}`}
              src={`https://www.youtube.com/embed/${id}`}
            ></iframe>
          </SplideSlide>
        ))}
      </Splide>
    </div>
  );
};

export default VideoCarousel;

Enter fullscreen mode Exit fullscreen mode

The code above uses the Splide library and the Splide Video extension in React to set up a video carousel. It defines the VideoCarousel component, configures the carousel options, and specifies an array of video IDs. The component renders a Splide component with SplideSlide components inside, each containing an embedded iframe with a YouTube video. The ref attribute is used to access the Splide instance. It creates a functional video carousel component using Splide and Splide Video extensions.

Now, In the src/App.js file, Replace the code with the following code:

import "./App.css";
import VideoCarousel from "./components/VideoCarousel";

function App() {

  return (
    <>
      <h1
        style={{
          textAlign: "center",
        }}
      >
      Video Carousel
      </h1>
      <div >
        <VideoCarousel/>
      </div>
    </>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

This code above is a component that serves as the application's main entry point. It imports the VideoCarousel component and the App.css file for styling.

To test the Video Carousel, visit localhost:3000 in your browser.

Video Carousel

Conclusion

Creating reusable components is vital to web development. A reusable carousel component can significantly enhance web projects' efficiency and maintainability. You used React and Splide.js in the article to construct a versatile and adaptable carousel component that seamlessly integrates into any web project.

Following a systematic approach, you demonstrated how to implement fundamental functionality, customize the styling, and incorporate additional features like autoplay and navigation. The result is a dynamic and flexible carousel component that enhances the user experience and adds visual appeal to web projects.

With the knowledge gained from this article, you can now create your reusable carousel component using React and Splide.js, elevating your web development skills to the next level.

References

Top comments (0)