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.
Join the DZone community and get the full member experience.
Join For FreeReact 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.
x
export default [{
title: 'Turn the music up!',
description: '',
},
{
title: 'Choose your music',
description: 'The world is full of music; why should you have to listen to music someone else chose?',
},
{
title: 'Unlimited, streaming, ad-free',
description: 'No arbitrary limits. No distractions.',
},
{
title: 'Mobile enabled',
description: 'Listen to your music on the go. This streaming service is available on all mobile platforms.',
}
];
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.
x
import React, { Component } from 'react';class LeftArrow extends Component {
render() {
return(
<div className='backArrow' onClick={this.props.goToPrevSlide}>
<i className='fa fa-angle-left fa-3x' aria-hidden='true'></i>
</div>
)
}
}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.
xxxxxxxxxx
goToPrevSlide() {
let index = this.state.activeIndex;
let length = this.state.length;if(index < 1) {
index = length - 1;
}
else {
index--;
}this.setState({
activeIndex: index
});
}goToNextSlide() {
let index = this.state.activeIndex;
let length = this.state.length;if(index === length - 1) {
index = 0
}
else {
index++;
}this.setState({
activeIndex: index
});
}
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.
xxxxxxxxxx
render() {
return (
<div className='slider'>
<div className='slider-items'>
<LeftArrow
goToPrevSlide={() => this.goToPrevSlide()}
/>
<div className='slider-text'>
<Slide
activeIndex={this.state.activeIndex}
/>
</div>
<RightArrow
goToNextSlide={() => this.goToNextSlide()}
/>
</div>
</div>
);
}
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.
xxxxxxxxxx
class Slide extends Component {
constructor(props) {
super(props);
this.state = {landing: landingData};
}render() {
return(
<section>
{
this.state.landing.map((s, index) =>
<div className={
index === this.props.activeIndex ? 'active' : 'slide'}
key={index}>
<h1>{s.title}</h1>
<p>{s.description}</p>
</div>
) }
</section>
)
}
}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.
x
className={index === this.props.activeIndex ? 'active' : 'inactive'}
.inactive {
display: none;
}
.active {
display: block;
}
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.
Opinions expressed by DZone contributors are their own.
Comments