3 Ways to Implement a Carousel in Nextjs

Chidi Eze

Introduction

Carousels, referred to as image sliders or sliders provides 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.

Sandbox

The completed project is on CodeSandbox.

View the source code on Github here.

Prerequisites

  • To swiftly follow this project, a basic knowledge of CSS, Javascript and React.js are required.
  • A good understanding of Next.js, but it's not strictly required.
  • Node.js installed on your computer.

Setting up Next.js Application

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

1npx 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:

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

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

Carousels don’t automatically create optimal slide dimensions. We will 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.

Bootstrap Carousel

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 start by installing react-bootstrap with the following command so that we have access to the carousel component:

1npm install react-bootstrap

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

1//public/Items.json
2 {
3 "items": {
4 "bootstrap": [
5 {
6 "id": 1,
7 "title": "Photography",
8 "body": "Bootstrap Carousel Example",
9 "imageUrl": "https://res.cloudinary.com/kizmelvin/image/upload/v1586799813/kizmelvin/persons_pigeon_nurkq2.jpg",
10 "docs": "https://getbootstrap.com/docs/4.0/components/carousel/"
11 },
12 {
13 "id": 2,
14 "title": "City Views",
15 "body": "Bootstrap Carousel Example",
16 "imageUrl": "https://res.cloudinary.com/kizmelvin/image/upload/v1587785064/kizmelvin/michael-BcgEo2CNeYA-unsplash_cdaruk.jpg",
17 "docs": "https://getbootstrap.com/docs/4.0/components/carousel/"
18 },
19 {
20 "id": 3,
21 "title": "Wild Life",
22 "body": "Bootstrap Carousel Example",
23 "imageUrl": "https://res.cloudinary.com/kizmelvin/image/upload/v1586799827/kizmelvin/brownlion_qm8hah.jpg",
24 "docs": "https://getbootstrap.com/docs/4.0/components/carousel/"
25 },
26 {
27 "id": 4,
28 "title": "Foods and Culture",
29 "body": "Bootstrap Carousel Example",
30 "imageUrl": "https://res.cloudinary.com/kizmelvin/image/upload/v1587870308/kizmelvin/edvin-johansson-5AylXcpJn1I-unsplash_lbhgod.jpg",
31 "docs": "https://getbootstrap.com/docs/4.0/components/carousel/"
32 }
33 ]
34 }
35 }

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

1//carousels/Bootstrap.js
2 import { useState } from "react";
3 import { items } from "../public/Items.json";
4 import { Carousel } from "react-bootstrap";
5 import "bootstrap/dist/css/bootstrap.min.css";
6 import styles from "../styles/Bootstrap.module.css";
7 export default function BootstrapCarousel() {
8 const { bootstrap } = items;
9 const [index, setIndex] = useState(0);
10 const handleSelect = (selectedIndex, e) => {
11 setIndex(selectedIndex);
12 };
13 return (
14 <Carousel activeIndex={index} onSelect={handleSelect}>
15 {bootstrap.map((item) => (
16 <Carousel.Item key={item.id} className={styles.itemP} interval={4000}>
17 <img src={item.imageUrl} alt="slides" />
18 <Carousel.Caption className={styles.caption}>
19 <h3>{item.title}</h3>
20 <p>{item.body}</p>
21 <button className="btn btn-danger">Visit Docs</button>
22 </Carousel.Caption>
23 </Carousel.Item>
24 ))}
25 </Carousel>
26 );
27 }

We 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 us clean it up, import our BootstrapCarousel component, and render it.

1//pages/index.js
2 import Head from "next/head";
3 import BootstrapCarousel from "../carousels/Bootstrap";
4 export default function Home() {
5 return (
6 <div>
7 <Head>
8 <title>Next.js Carousels</title>
9 <meta name="description" content="Generated by create next app" />
10 <link rel="icon" href="/favicon.ico" />
11 </Head>
12 <main>
13 <BootstrapCarousel />
14 </main>
15 </div>
16 );
17 }

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

Visit the documentation for more carousel configurations and customizations.

Elastic Carousel

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 install the library with the following command:

1npm install react-elastic-carousel

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

1//public/Items.json
2 {
3 "items": {
4 "bootstrap": [
5 #bootstrap objects
6 ],
7 "elastic": [
8 {
9 "id": 1,
10 "title": "Photoshoots",
11 "imageUrl": "https://res.cloudinary.com/kizmelvin/image/upload/v1645530542/kizmelvin/Carousel%20assets/luwadlin-bosman-J1oObe7WWjk-unsplash_f56oh3.jpg"
12 },
13 {
14 "id": 2,
15 "title": "Adventure",
16 "imageUrl": "https://res.cloudinary.com/kizmelvin/image/upload/v1645529949/kizmelvin/Carousel%20assets/ali-kazal-q9rpNOd1hcI-unsplash_fhaqzq.jpg"
17 },
18 {
19 "id": 3,
20 "title": "Events",
21 "imageUrl": "https://res.cloudinary.com/kizmelvin/image/upload/v1645530199/kizmelvin/Carousel%20assets/slim-emcee-jzdOX0XkXr8-unsplash_zocsdq.jpg"
22 },
23 {
24 "id": 4,
25 "title": "Discovery",
26 "imageUrl": "https://res.cloudinary.com/kizmelvin/image/upload/v1645530863/kizmelvin/Carousel%20assets/francisco-t-santos-YRcioOWh4mA-unsplash_1_yoowse.jpg"
27 },
28 {
29 "id": 5,
30 "title": "Sports",
31 "imageUrl": "https://res.cloudinary.com/kizmelvin/image/upload/v1645531100/kizmelvin/Carousel%20assets/markus-spiske-WUehAgqO5hE-unsplash_zi9wvh.jpg"
32 }
33 ]
34 }
35 }

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

1//carousels/Elastic.js
2 import { items } from "../public/Items.json";
3 import Carousel from "react-elastic-carousel";
4 import styles from "../styles/Elastic.module.css";
5 const breakPoints = [
6 { width: 1, itemsToShow: 1 },
7 { width: 550, itemsToShow: 1, itemsToScroll: 2 },
8 { width: 768, itemsToShow: 2 },
9 { width: 1200, itemsToShow: 3 }
10 ];
11 export default function ElasticCarousel() {
12 const { elastic } = items;
13 return (
14 <div className={styles.container}>
15 <div>
16 <h1>React Elastic Carousel Example</h1>
17 </div>
18 <hr className={styles.seperator} />
19 <div className={styles.contWrapper}>
20 <Carousel breakPoints={breakPoints}>
21 {elastic.map((item) => (
22 <div
23 key={item.id}
24 className={styles.card}
25 style={{ backgroundImage: `url(${item.imageUrl})` }}
26 >
27 <div className={styles.title}>
28 <h3>{item.title} </h3>
29 </div>
30 </div>
31 ))}
32 </Carousel>
33 </div>
34 </div>
35 );
36 }

We 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 import the ElasticCarousel component and render it right after the BootstrapCarousel element.

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

React Responsive Carousel

This is an excellent carousels component with a robust amount of options and configurations. It supports thumbnails, vertical scrolling, and a fading effect too. But it doesn’t support dragging.

Let's install the package with the following command:

1npm install react-responsive-carousel

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

1//public/Items.json
2 {
3 "items": {
4 "bootstrap": [
5 #bootstrap carousel objects
6 ],
7 "elastic": [
8 #elastic carousel objects
9 ],
10 "responsive": [
11 {
12 "id": 1,
13 "title": "Swiper Carousel Example",
14 "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",
15 "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"
16 },
17 {
18 "id": 2,
19 "title": "Swiper Carousel Example",
20 "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",
21 "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"
22 },
23 {
24 "id": 3,
25 "title": "Swiper Carousel Example",
26 "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",
27 "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"
28 }
29 ]
30 }
31 }

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

1//carousels/Responsive.js
2 import { Carousel } from "react-responsive-carousel";
3 import { items } from "../public/Items.json";
4 import "react-responsive-carousel/lib/styles/carousel.min.css";
5 import styles from "../styles/Responsive.module.css";
6 export default function ResponsiveCarousel() {
7 const { responsive } = items;
8 return (
9 <div className={styles.container}>
10 <Carousel
11 showArrows={true}
12 showIndicators={true}
13 infiniteLoop={true}
14 dynamicHeight={false}
15 className={styles.mySwiper}
16 >
17 {responsive.map((item) => (
18 <div key={item.id} className={styles.swipItem}>
19 <div className={styles.imgBox}>
20 <img src={item.imageUrl} alt="slides" />
21 </div>
22 <div className={styles.detail}>
23 <h2>{item.title}</h2>
24 <p>{item.text}</p>
25 </div>
26 </div>
27 ))}
28 </Carousel>
29 </div>
30 );
31 }

We 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.

1#pages/index.js
2 import Head from "next/head";
3 import BootstrapCarousel from "../carousels/Bootstrap";
4 import ElasticCarousel from "../carousels/Elastic";
5 import ResponsiveCarousel from "../carousels/Responsive";
6 export default function Home() {
7 return (
8 <div>
9 <Head>
10 <title>Next.js Carousels</title>
11 <meta name="description" content="Generated by create next app" />
12 <link rel="icon" href="/favicon.ico" />
13 </Head>
14 <main>
15 <BootstrapCarousel />
16 <ElasticCarousel />
17 <ResponsiveCarousel />
18 </main>
19 </div>
20 );
21 }

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

Conclusion

We 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 different documentations.

It is also worth noting that carousels are not entirely compliant with web accessibility standards.

Resources

Chidi Eze

Frontend Engineer

I'm a frontend engineer and a technical content creator, I love it once it has to do with javascript.