Build A Reusable Carousel With React And Splide.js
Tags: react, tutorial, javascript, frontend
Published: 2023-06-13 22:23:42

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a74syh898aih10hxdtah.gif)



In this article, you will build a reusable carousel component using [React](https://react.dev/) and [Splide.Js](https://splidejs.com/) — 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:

```javaScript
npm install @splidejs/splide
```
- **Hosting Files**

You can download the Splide package from the following link:
[Download](https://github.com/Splidejs/splide/releases/latest/)

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

```javaScript
<script src="path-to-the-file/splide.min.js"></script>
```

- **CDN**

You can also include this library from CDN:

[jsDelivr](https://www.jsdelivr.com/package/npm/@splidejs/splide?path=dist)

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](https://splidejs.com/integration/react-splide/)
[Vue Splide](https://splidejs.com/integration/vue-splide/)
[Svelte Splide](https://splidejs.com/integration/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.


```javaScript
npx create-react-app splidereacttutorial && cd splidereacttutorial
```

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:

```javaScript
$ npm install @splidejs/splide
```

# 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:

```javaScript
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;

```

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:


```javaScript
.App {
  display: flex;
  justify-content: center;
  align-items: center;
}
```

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:

```javaScript

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;

```

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:

```javaScript
npm start
```
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bqa3dlk7gkwqwk746g9i.gif)

# Creating Auto-scroll Carousel

To create an auto-scroll carousel, you will use The [Auto Scroll extension](https://github.com/Splidejs/splide-extension-auto-scroll) 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:

```javaScript
npm install @splidejs/splide-extension-auto-scroll
```

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

```javaScript
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;

```
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zpse3g3kt024p9i67wwi.gif)

# 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: 

```javaScript
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>
    </>
  );
}

```

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:

```javaScript
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;

```

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a74syh898aih10hxdtah.gif)

# Creating a Video Carousel

To create the Video Carousel, you will use The [Video extension](https://github.com/Splidejs/splide-extension-video)

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

```javaScript
npm install @splidejs/splide-extension-video

```

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

```javaScript

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;

```

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:

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

function App() {

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

export default App;
```

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jqr7h31w0e1dhf0cfvfy.gif)

# 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

- [Splidejs Documentation](https://splidejs.com/)

- [Build A Reusable Carousel With Vue And Splide.Js](https://blog.openreplay.com/build-a-reusable-carousel-with-vue-and-splidejs/)