DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • How to Build Scalable Mobile Apps With React Native: A Step-by-Step Guide
  • Migrating from React Router v5 to v6: A Comprehensive Guide
  • React Callback Refs: What They Are and How to Use Them
  • Why React Router 7 Is a Game-Changer for React Developers

Trending

  • Automatic Code Transformation With OpenRewrite
  • The Cypress Edge: Next-Level Testing Strategies for React Developers
  • Zero Trust for AWS NLBs: Why It Matters and How to Do It
  • How to Convert XLS to XLSX in Java
  1. DZone
  2. Coding
  3. JavaScript
  4. How to Build a Responsive React Carousel

How to Build a Responsive React Carousel

We go over how to build a carousel to display media in your web or mobile app using React, as well as the best plugins to use to make the process easier.

By 
Fayaz Shaik user avatar
Fayaz Shaik
·
Feb. 01, 21 · Tutorial
Likes (5)
Comment
Save
Tweet
Share
32.2K Views

Join the DZone community and get the full member experience.

Join For Free

React Carousel

A carousel in React is a slideshow, or a series, of several images. A React carousel is built with the help of CSS transitions and JavaScript coding. A carousel in React can include any element, like image, text, videos, markups, etc. In React, you can create a carousel that has an interactive control like a forward and backward button and image indicators.

React supports a vast collection of highly dynamic and interactive carousels. Also, it has several libraries from which you can build a carousel. These libraries are linked to the React app as an additional plugin, and you can start using them to make a carousel. You can create any type of image carousel with interactive controls and also without them. In React, carousels do not determine their dimensions on their own; you will need to specify them. This is because you might add custom stylizing, transitions, and text, all these are required manual modifications. The indicators and elements are not essential to be passed explicitly while making a carousel in React; you can add them anywhere.

Building a React Carousel

1. Create a Data Containing Object

Initially, you will need to make a component that can hold all the data of the carousel. This component should be an array that lets you set the slides and that will change the image or text accordingly.  

JavaScript
 




x


 
1
export default [{
2
        title: 'Turn the music up!',
3
        description: '',
4
    },
5
    {
6
        title: 'Choose your music',
7
        description: 'The world is full of music; why should you have to listen to music someone else chose?',
8
    },
9
    {
10
        title: 'Unlimited, streaming, ad-free',
11
        description: 'No arbitrary limits. No distractions.',
12
    },
13
    {
14
        title: 'Mobile enabled',
15
        description: 'Listen to your music on the go. This streaming service is available on all mobile platforms.',
16
    }
17
];


2. Components of the Carousel

Next, you will have to create components for the Carousel. Those components will contain all the interactive elements, like the indicators, buttons, next and previous buttons, etc. Let's include forward and previous buttons as arrows. For this, you should have the images for the arrows you will be using in the carousel. Both the arrows are going to be similar; only the functions will be different. You will have to add <div> functions that will contain the images you will be using for the buttons. You can also add an onclick function so that they will execute when clicked.

JavaScript
 




x
9


 
1
import React, { Component } from 'react';class LeftArrow extends Component {
2
 render() {
3
   return(
4
     <div className='backArrow' onClick={this.props.goToPrevSlide}>
5
       <i className='fa fa-angle-left fa-3x' aria-hidden='true'></i>
6
     </div>
7
   )
8
 }
9
}export default LeftArrow;


After creating navigation buttons, you will have to create another component that will have the code for switching the slides and the navigation buttons. Here you will add an onclick behavior to the navigation arrows. To display the slideshow in a continuous format, you will need to make a never-ending loop. For instance, you are on the last slide, and after that, if you click the next button, you will be shown the first slide and vice versa.

Before starting to create the components, you are supposed to build two additional states. 

These states will help to simplify the following procedure. So, first, create an activeIndex state. This state will display the current slide on the web page in which the output is being shown. You can put the value to an index number and the respective slide will be displayed on the web page. Secondly, create a length state; this will provide the size of the array of the carousel. This will help to determine from which slide you are supposed to loop the slides.

You have created the states required for the React carousel now, so you can start defining the functions. These functions will have the logic that allows for the use of arrows to navigate through the slides. You can pass the props to the arrow functions describing the control functions.

goToNextSlide() and goToPrevSlide() are the two functions that will have the logic to move forward and backward in the slideshow. They will have the logic to increment or decrement the index number of the slides.

JavaScript
 




xxxxxxxxxx
1
41


 
1
goToPrevSlide() {
2
   let index = this.state.activeIndex;
3
   let length = this.state.length;if(index < 1) {
4
     index = length - 1;
5
   }
6
   else {
7
     index--;
8
   }this.setState({
9
     activeIndex: index
10
   });
11
 }goToNextSlide() {
12
     let index = this.state.activeIndex;
13
     let length = this.state.length;if(index === length - 1) {
14
       index = 0
15
     }
16
     else {
17
       index++;
18
     }this.setState({
19
       activeIndex: index
20
     });
21
 }


Here, an if-statement is used to perform the looping. With the help of looping, you will be redirected to the first slide after clicking the 'next' arrow on the last slide. After this, you will have to determine the components that will be displayed on the user's screen. Here you will show left and right arrows, slide indicators, and pass the props of the functions that were created previously.

JavaScript
 




xxxxxxxxxx
1
37


 
1
render() {
2

          
3
return (
4

          
5
<div className='slider'>
6

          
7
<div className='slider-items'>
8

          
9
<LeftArrow
10

          
11
goToPrevSlide={() => this.goToPrevSlide()}
12

          
13
/>
14

          
15
<div className='slider-text'>
16

          
17
<Slide
18

          
19
activeIndex={this.state.activeIndex}
20

          
21
/>
22

          
23
</div>
24

          
25
<RightArrow
26

          
27
goToNextSlide={() => this.goToNextSlide()}
28

          
29
/>
30

          
31
</div>
32

          
33
</div>
34

          
35
);
36

          
37
}


The final component required is for the date of the slides. This competent will access the data of the individual slides and display them on the screen of the browser. This particular component will return a function that can display the information of the array.

JavaScript
 




xxxxxxxxxx
1
39


 
1
class Slide extends Component {
2
 constructor(props) {
3
   super(props);
4
   this.state = {landing: landingData};
5
 }render() {
6
   return(
7
     <section>
8
     {
9
       this.state.landing.map((s, index) =>
10
         <div className={
11
           index === this.props.activeIndex ? 'active' : 'slide'}
12
           key={index}>
13
             <h1>{s.title}</h1>
14
             <p>{s.description}</p>
15
         </div>
16
       ) }
17
       </section>
18
   )
19
 }
20
}export default Slide;


3. Attach CSS to the Carousel

The final step is to insert CSS into the carousel. Without this, the Carousel will look very messed up. You will see all the slides at once to avoid this; you will have to display the active slides only. For this, create a class that will consist of the activeIndex state to specify the index of the active slide.

CSS
 




x


 
1
className={index === this.props.activeIndex ? 'active' : 'inactive'} 
2

          
3
.inactive {
4
    display: none;
5
}
6

          
7
.active {
8
    display: block;
9
}


In the above CSS file, only the active index slides are shown, and the inactive are kept hidden. This arranges the slides in an organized way to avoid confusion.

React Carousel Plugins

React supports various plugins for the development of carousels. These plugins extend the DOM management capability and enable you the opportunity to create an extraordinary carousel. With the help of plugins, the modification through CSS is reduced in a way that saves on development time.

1. React-Responsive-Carousel

React-Responsive-Carousel is a user-friendly plugin that has slideshow customization capabilities. You can use the custom navigation button, thumbnails, indications, etc., in your project. This plugin is compatible with mobile devices and features navigation in upward and downward directions. It can include custom animations, slides, effects, transition duration, and many more exciting elements.

Features:

  • Mobile touch swiping.
  • Keyboard control.
  • Endless looping.
  • Compatible with external control.
  • Autoplay capability.
  • Texts, images, graphics, videos, etc. can be included.

You can install this plugin with the command:

yarn add react-responsive-carousel  

2. Pure React Carousel

Pure React Carousel is a library that has all the required elements to build a fully-featured React carousel. It has the support of mobile touch and customizable components. You can manage the carousel components in the DOM as you require, in order to maintain the organization. It also lets you change the mass of the class, components, functions, etc., so that you can create unique code. You can install this plugin with npm i -S pure-react-carousel and start importing the components into the project folder.  

3. React Swipe

React Swipe is a customizable and straightforward image carousel plugin for React. It has mobile compatibility and interactive architecture. It is preferred for effortlessly building simple React carousels. The drawback is that it does not support vertical navigation.

Features:

  • Infinite looping.
  • Auto slideshow.
  • Simple customizations.
  • Call-back.
  • Ending transitions.

4. React-Image-Gallery

React-Image-Gallery is a scalable react carousel builder for beginner developers. This builder does not need a complicated installation and it is easy to use. It's only 8KB also has enabled mobile controls and thumb navigation.

Notable features:

  • Autoplay.
  • Horizontal scrolling.
  • Fully customizable.
  • Gestures.
  • Fullscreen support.
  • Slide on swipe capability.
  • Custom slides.

5. React Slick

React Slick is a popular library for developing carousels in React. It has gained a lot of popularity because of its many services. It has vertical and horizontal sliding. The elements you will find are entirely customizable and it is compatible with CSS3.

Top Features:

  • Callback.
  • Lazy loading.
  • Responsive.
  • Navigation in both directions.
  • Mouse dragging.
  • Navigation through arrow keys.
  • Filter and unfilter slides.

Benefits of React Carousels

Interactive Design

React carousels are designed with the best transitions and custom animations that make your app compelling and unique. Showcasing React carousels makes your React app more interactive, as the user can navigate through the app to explore. Additionally, a carousel can contain any type of media. That is, it can be an image, text, or even a video. All this improves the quality of the app you are developing.

Saves Time for the User

When used appropriately, React carousels can be very handy. When you use an automatic slide show using the React carousel, you can save the user time. By avoiding the need to click, you can display the required information within the slideshow. You can show the key features or services on the top of the web app as a React carousel, so that users do not miss anything essential.

React Carousel as a Comparison Tool

React carousels can be used for easy comparison between several products or services. Let's suppose you are comparing smartphones. Then you can list their specifications side-by-side, such that you can compare the aspects effortlessly. If there's a lot of info, you can split them into distinct slides and attractively display them.

Clean Design

While keeping the text short, the slides look interesting. This is because they are easy to read and understand. As you know, no one likes to read long and confusing text. So, it is recommended to make the slides that have less text and more fascinating designs. Users highly appreciate this clean design of that React carousels bring.

Final Verdict

React carousels are another element form the massive collection of features of React. They have great popularity in eCommerce services. In eCommerce websites or apps, they are involved in improving the functionality of the app. A React carousel also gets more engagement than other elements of a UI. Hence every shopping or eCommerce site has several carousels in their display.

Creating a React carousel is a tedious job, but hard work is not wasted. You get a seamless architecture for your React app. Also, with the availability of plugins and React libraries, you can design carousels in no time. The only catch is that you are not permitted to modify everything in a plugin, as compared to development from scratch. Overall, React carousels are an excellent element to include in your React projects.

React (JavaScript library) Build (game engine) mobile app Element

Opinions expressed by DZone contributors are their own.

Related

  • How to Build Scalable Mobile Apps With React Native: A Step-by-Step Guide
  • Migrating from React Router v5 to v6: A Comprehensive Guide
  • React Callback Refs: What They Are and How to Use Them
  • Why React Router 7 Is a Game-Changer for React Developers

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!