Skip to content

3 Ways to Implement a Carousel in Next.js

Carousels, referred to as image sliders or sliders, provide an improved visual experience on websites by highlighting important aspects of a product, service or value proposition.

This post discusses three different ways to add a carousel to our Next.js application.

The completed project is on CodeSandbox.

View the source code on Github here.

To follow this project, you’ll need:

  • Basic knowledge of CSS, Javascript, and React.js.
  • A good understanding of Next.js, but it’s not strictly required.
  • Node.js installed on your computer.

Before we dive into the different methods of adding a carousel, it’s crucial to understand that while carousels can provide a dynamic visual element to your website, they also come with some performance and accessibility concerns. Thus, implementing them efficiently and in a user-friendly manner is vital.

We’ll run the following terminal command to create the Next.js app in a folder called next-carousels:

npx create-next-app next-carousels

Follow the prompts to complete the process, then navigate into the application directory and start the dev server with the following:

cd next-carousels // to navigate into the project directory
npm run dev // to run the dev server

In the browser, we should have the app live on localhost:3000.

welcome-next

Carousels don’t automatically create optimal slide dimensions. We’ll use additional utilities or custom styles to appropriately size it.

We’ll use component level styling. Learn how to use CSS Modules or see other Next.js built-in CSS support here.

Built with CSS 3D transformations, this carousel automatically cycles through a series of images, text, or custom markup. It supports next/prev controls and also supports indicators.

We’ll start by installing react-bootstrap with the following command so that we have access to the carousel component:

npm install react-bootstrap

Next, let’s go to the public folder and create an Items.json file, which will house our image data. We’ll structure our JSON object like below:


    //public/Items.json
    {
      "items": {
        "bootstrap": [
          {
            "id": 1,
            "title": "Photography",
            "body": "Bootstrap Carousel Example",
            "imageUrl": "https://res.cloudinary.com/kizmelvin/image/upload/v1586799813/kizmelvin/persons_pigeon_nurkq2.jpg",
            "docs": "https://getbootstrap.com/docs/4.0/components/carousel/"
          },
          {
            "id": 2,
            "title": "City Views",
            "body": "Bootstrap Carousel Example",
            "imageUrl": "https://res.cloudinary.com/kizmelvin/image/upload/v1587785064/kizmelvin/michael-BcgEo2CNeYA-unsplash_cdaruk.jpg",
            "docs": "https://getbootstrap.com/docs/4.0/components/carousel/"
          },
          {
            "id": 3,
            "title": "Wild Life",
            "body": "Bootstrap Carousel Example",
            "imageUrl": "https://res.cloudinary.com/kizmelvin/image/upload/v1586799827/kizmelvin/brownlion_qm8hah.jpg",
            "docs": "https://getbootstrap.com/docs/4.0/components/carousel/"
          },
          {
            "id": 4,
            "title": "Foods and Culture",
            "body": "Bootstrap Carousel Example",
            "imageUrl": "https://res.cloudinary.com/kizmelvin/image/upload/v1587870308/kizmelvin/edvin-johansson-5AylXcpJn1I-unsplash_lbhgod.jpg",
            "docs": "https://getbootstrap.com/docs/4.0/components/carousel/"
          }
        ]
      }
    }
   
Code language: JSON / JSON with Comments (json)

We’ll create a carousels folder in the root directory and inside the folder, create Bootstrap.js file with the following code:


    //carousels/Bootstrap.js
    import { useState } from "react";
    import { items } from "../public/Items.json";
    import { Carousel } from "react-bootstrap";
    import "bootstrap/dist/css/bootstrap.min.css";
    import styles from "../styles/Bootstrap.module.css";
    export default function BootstrapCarousel() {
      const { bootstrap } = items;
      const [index, setIndex] = useState(0);
      const handleSelect = (selectedIndex, e) => {
        setIndex(selectedIndex);
      };
      return (
        <Carousel activeIndex={index} onSelect={handleSelect}>
          {bootstrap.map((item) => (
            <Carousel.Item key={item.id} className={styles.itemP} interval={4000}>
              <img src={item.imageUrl} alt="slides" />
              <Carousel.Caption className={styles.caption}>
                <h3>{item.title}</h3>
                <p>{item.body}</p>
                <button className="btn btn-danger">Visit Docs</button>
              </Carousel.Caption>
            </Carousel.Item>
          ))}
        </Carousel>
      );
    }

Code language: JavaScript (javascript)

We’ve imported our JSON object in the above code block, and got the Carousel component from the react-bootstrap module.

Then, we looped through the bootstrap array destructured from items and rendered a Carousel component.

Also, we imported bootstrap minified CSS and our custom styles from styles/Bootstrap.module.css.

In index.js, let’s clean it up, import our BootstrapCarousel component, and render it.


    //pages/index.js
    import Head from "next/head";
    import BootstrapCarousel from "../carousels/Bootstrap";
    export default function Home() {
      return (
        <div>
          <Head>
            <title>Next.js Carousels</title>
            <meta name="description" content="Generated by create next app" />
            <link rel="icon" href="/favicon.ico" />
          </Head>
          <main>
            <BootstrapCarousel />
          </main>
        </div>
      );
    }

Code language: JavaScript (javascript)

Now, if we go over to the browser, we’ll see a functional carousel.

first-carousel

Visit the documentation for more carousel configurations and customizations.

Elastic Carousel is a flexible and responsive carousel component; it somehow does not support automatic cycling through content but has full support for RTL(right to left) rendering and animations.

As a first step, we’ll install the library with the following command:

npm install react-elastic-carousel 

Next, we’ll nest another set of data in our Items.json for the elastic carousel just like we did for the bootstrap carousel.


    //public/Items.json
    {
      "items": {
        "bootstrap": [
          #bootstrap objects
        ],
        "elastic": [
          {
            "id": 1,
            "title": "Photoshoots",
            "imageUrl": "https://res.cloudinary.com/kizmelvin/image/upload/v1645530542/kizmelvin/Carousel%20assets/luwadlin-bosman-J1oObe7WWjk-unsplash_f56oh3.jpg"
          },
          {
            "id": 2,
            "title": "Adventure",
            "imageUrl": "https://res.cloudinary.com/kizmelvin/image/upload/v1645529949/kizmelvin/Carousel%20assets/ali-kazal-q9rpNOd1hcI-unsplash_fhaqzq.jpg"
          },
          {
            "id": 3,
            "title": "Events",
            "imageUrl": "https://res.cloudinary.com/kizmelvin/image/upload/v1645530199/kizmelvin/Carousel%20assets/slim-emcee-jzdOX0XkXr8-unsplash_zocsdq.jpg"
          },
          {
            "id": 4,
            "title": "Discovery",
            "imageUrl": "https://res.cloudinary.com/kizmelvin/image/upload/v1645530863/kizmelvin/Carousel%20assets/francisco-t-santos-YRcioOWh4mA-unsplash_1_yoowse.jpg"
          },
          {
            "id": 5,
            "title": "Sports",
            "imageUrl": "https://res.cloudinary.com/kizmelvin/image/upload/v1645531100/kizmelvin/Carousel%20assets/markus-spiske-WUehAgqO5hE-unsplash_zi9wvh.jpg"
          }
        ]
      }
    }
    
Code language: JSON / JSON with Comments (json)

Next, in the carousels folder, let’s create an Elastic.js file and build the carousel.


    //carousels/Elastic.js
    import { items } from "../public/Items.json";
    import Carousel from "react-elastic-carousel";
    import styles from "../styles/Elastic.module.css";
    const breakPoints = [
      { width: 1, itemsToShow: 1 },
      { width: 550, itemsToShow: 1, itemsToScroll: 2 },
      { width: 768, itemsToShow: 2 },
      { width: 1200, itemsToShow: 3 }
    ];
    export default function ElasticCarousel() {
      const { elastic } = items;
      return (
        <div className={styles.container}>
          <div>
            <h1>React Elastic Carousel Example</h1>
          </div>
          <hr className={styles.seperator} />
          <div className={styles.contWrapper}>
            <Carousel breakPoints={breakPoints}>
              {elastic.map((item) => (
                <div
                  key={item.id}
                  className={styles.card}
                  style={{ backgroundImage: `url(${item.imageUrl})` }}
                >
                  <div className={styles.title}>
                    <h3>{item.title} </h3>
                  </div>
                </div>
              ))}
            </Carousel>
          </div>
        </div>
      );
    }
Code language: JavaScript (javascript)

We’ve destructured elastic from the items dataset we imported above. Afterwards, we looped through the elastic json objects and used the Carousel component we imported from react-elastic-carousel to render the second carousel.

In pages/index.js, we’ll import the ElasticCarousel component and render it right after the BootstrapCarousel element.

second-carousel

In the browser, the project should look like the above. Learn more about this carousel here.

This is an excellent carousels component with a robust amount of options and configurations. It supports thumbnails, vertical scrolling and a fading effect, but not dragging.

Let’s install the package with the following command:

npm install react-responsive-carousel

We’ll update the data set in the Item.json file for the responsive carousel.


    //public/Items.json
    {
      "items": {
        "bootstrap": [
         #bootstrap carousel objects
        ],
        "elastic": [
        #elastic carousel objects  
        ],
        "responsive": [
          {
            "id": 1,
            "title": "Swiper Carousel Example",
            "text": "Lorem ipsum dolor sit amet consectetur adipisicing elit. Iste quos mollitia sed quod consectetur at quam dolore praesentium neque eos assumenda iusto nam laborum laboriosam odio blanditiis possimus accusantium recusandae porro exercitationem itaque",
            "imageUrl": "https://res.cloudinary.com/kizmelvin/image/upload/w_1000,c_fill,ar_1:1,g_auto,r_max,bo_5px_solid_red,b_rgb:262c35/v1597364662/kizmelvin/ussama-azam-hlg-ltdCoI0-unsplash_ttfjib.jpg"
          },
          {
            "id": 2,
            "title": "Swiper Carousel Example",
            "text": "Lorem ipsum dolor sit amet consectetur adipisicing elit. Iste quos mollitia sed quod consectetur at quam dolore praesentium neque eos assumenda iusto nam laborum laboriosam odio blanditiis possimus accusantium recusandae porro exercitationem itaque",
            "imageUrl": "https://res.cloudinary.com/kizmelvin/image/upload/w_1000,c_fill,ar_1:1,g_auto,r_max,bo_5px_solid_red,b_rgb:262c35/v1645530199/kizmelvin/Carousel%20assets/slim-emcee-jzdOX0XkXr8-unsplash_zocsdq.jpg"
          },
          {
            "id": 3,
            "title": "Swiper Carousel Example",
            "text": "Lorem ipsum dolor sit amet consectetur adipisicing elit. Iste quos mollitia sed quod consectetur at quam dolore praesentium neque eos assumenda iusto nam laborum laboriosam odio blanditiis possimus accusantium recusandae porro exercitationem itaque",
            "imageUrl": "https://res.cloudinary.com/kizmelvin/image/upload/w_1000,c_fill,ar_1:1,g_auto,r_max,bo_5px_solid_red,b_rgb:262c35/v1645534321/kizmelvin/Carousel%20assets/luwadlin-bosman-J1oObe7WWjk-unsplash_f56oh3.jpg"
          }
        ]
      }
    }

Code language: JSON / JSON with Comments (json)

Now, we’ll create a Responsive.js file inside the carousels folder and implement the carousel.


    //carousels/Responsive.js
    import { Carousel } from "react-responsive-carousel";
    import { items } from "../public/Items.json";
    import "react-responsive-carousel/lib/styles/carousel.min.css";
    import styles from "../styles/Responsive.module.css";
    export default function ResponsiveCarousel() {
      const { responsive } = items;
      return (
        <div className={styles.container}>
          <Carousel
            showArrows={true}
            showIndicators={true}
            infiniteLoop={true}
            dynamicHeight={false}
            className={styles.mySwiper}
          >
            {responsive.map((item) => (
              <div key={item.id} className={styles.swipItem}>
                <div className={styles.imgBox}>
                  <img src={item.imageUrl} alt="slides" />
                </div>
                <div className={styles.detail}>
                  <h2>{item.title}</h2>
                  <p>{item.text}</p>
                </div>
              </div>
            ))}
          </Carousel>
        </div>
      );
    }

Code language: JavaScript (javascript)

We’ve imported the Carousel component from react-responsive-carousel and used it to display our responsive json object. Also, notice that we brought in the corresponding CSS module from the Styles folder.

Import the ResponsiveCarousel component inside index.js and render it after the ElasticCarousel.

    #pages/index.js
    import Head from "next/head";
    import BootstrapCarousel from "../carousels/Bootstrap";
    import ElasticCarousel from "../carousels/Elastic";
    import ResponsiveCarousel from "../carousels/Responsive";
    export default function Home() {
      return (
        <div>
          <Head>
            <title>Next.js Carousels</title>
            <meta name="description" content="Generated by create next app" />
            <link rel="icon" href="/favicon.ico" />
          </Head>
          <main>
            <BootstrapCarousel />
            <ElasticCarousel />
            <ResponsiveCarousel />
          </main>
        </div>
      );
    }
Code language: HTML, XML (xml)

Then in the browser, we should now see the three different carousels with different options and customizations.

third-carousel

When implementing carousels in Next.js or any other framework, always consider the impact on performance and user experience. While they can be visually appealing, a poorly implemented carousel might result in longer loading times and difficulties for users in navigating the content. Always prioritize user experience and test the carousel’s performance across different devices and browsers.

We’ve discussed three different ways to add a carousel in a next.js projects. Although this post covers the basic implementation of these carousels, there are more configurations in their respective documentations.

It’s also worth noting that carousels aren’t entirely compliant with web accessibility standards.

Back to top

Featured Post