How to create a Responsive Carousel in React JS

  • react-js
  • 79 Views
  • 4 Min Read
  • 8 Jul 2024

In this article, you will learn how to create a responsive carousel with React. Carousels are essential for websites like e-commerce to showcase products, highlight features, and capture users' attention.

 

I am confident that using this guide, you will be able to build a responsive carousel that adjusts to multiple screen sizes.

 

Let's dive in and get started!

 

Table of contents:

 

  1. Setting Up Your React Project for Carousel Development
  2. Installing Dependencies for React Carousel
  3. Creating the Carousel Component in React JS
  4. Styling Your Carousel (Optional)
  5. Import the Carousel Component in the App.js Component 
  6. Run your Application
  7. Enhance Your Carousel: Advanced Features for Improved Performance
  8. Exploring More Features to Manage Carousel Behavior Effectively
 

 

 

First, create a new React project using the Create React App:

 
npx create-react-app responsive-carousel  // This command creates a new React project named 'responsive-carousel'

cd responsive-carousel  // This command navigates into the newly created project directory
 

After starting your project, keep your code clean. Remove unnecessary files from your project folder. Organize and simplify the 'index.js' file. Also, trim down the 'App.js' file to include only essential code for better clarity and performance.

 

Your folder structure, index.js, and app.js file should look like this:

 

Carousel Folder Structure

 

 

 

Next, install the react-responsive-carousel package, which we'll use to create our carousel:

 
npm install react-responsive-carousel

 

After installing the package, it's important to confirm it is perfectly installed in your project. You can do this by checking your 'package.json' file to ensure the package is added inside dependencies. Look for 'react-responsive-carousel': 'Version' under dependencies. If you find it there, it indicates that the package has been successfully installed. if it's not listed, you'll need to reinstall it again.

 

 

 

Now, let's create a new file named MyCarousel.jsx in the src directory and define our carousel component:

 

To set up the carousel in our project, we first need to import the Carousel component from the 'react-responsive-carousel' package. Additionally, we must import the carousel CSS within the MyCarousel component file.

 

Include these two lines in your carousel component.

 

MyCarousel.Jsx

 
import { Carousel } from 'react-responsive-carousel';
import 'react-responsive-carousel/lib/styles/carousel.min.css';
 

Next, simply insert your desired images within the JSX code of your MyCarousel.jsx file, placed between the Carousel tags.

 

MyCarousel.Jsx file

 
import React from 'react';
import { Carousel } from 'react-responsive-carousel';
import 'react-responsive-carousel/lib/styles/carousel.min.css';

const MyCarousel = () => {
    return (
        <Carousel >
            <div>
                <img src="https://images.unsplash.com/photo-1612817159949-195b6eb9e31a?q=80&w=2070&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D" alt="Watch 1" />
            </div>
            <div>
                <img src="https://images.unsplash.com/photo-1601801958048-aa2e1c3e21e3?q=80&w=2070&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D" alt="Watch 2" />
            </div>
            <div>
                <img src="https://images.pexels.com/photos/190819/pexels-photo-190819.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1" alt="Watch 3" />
            </div>
            <div>
                <img src="https://images.unsplash.com/photo-1617317376997-8748e6862c01?q=80&w=2070&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D" alt="Watch 4" />
            </div>
        </Carousel>
    );
};

export default MyCarousel;

 

In the above code, we create a carousel component that displays four images of watches. The Carousel component wraps these <div> elements to enable sliding through the images.

 

 

 

You can add custom styles to your carousel by modifying the CSS file. For example:

 

App.css

 
.carousel {
    max-width: 800px;
    display: grid;
    place-items: center;
    border-radius: 8px;
}

.App {
    display: grid;
    place-items: center;
}

img {
    width: 100%;
    border-radius: 8px;
}
 
The carousel class is used internally by the React Responsive Carousel library to style and manage the appearance and behavior of the carousel component, even if you haven't specifically defined it in your own components.
 
 

 

To use the carousel in your application, import the Carousel component into your App.js file and render it:

 

App.js

 
import './App.css';
import React from 'react';
import MyCarousel from './MyCarousel';

function App() {
    return (
        <>
            <div className="App">
                <h1>Responsive Carousel</h1>
                <MyCarousel />
            </div>
        </>
    );
}

export default App;
 
 

6. Run Your Application

 

Finally, start your React development server and open your browser to view the carousel.

 
npm start
 

Navigate to http://localhost:3000 in your browser, and you will see your responsive carousel in action!

 

Project

 

Our app looks good! The carousel is working smoothly, showing images nicely. Everything seems to be working just as it should.

 

Okay, Great!

 

Now we know some additional functionalities to make our carousel project even more exciting. While we already have the basic setup thanks to the Carousel package, understanding these additional features will allow us to interact with our project more effectively.

 

 

7. Enhance Your Carousel: Advanced Features for Improved Performance

 

Customize the carousel further by removing arrows, enabling autoplay, implementing infinite loop functionality, and specifying the interval duration in milliseconds using the interval property. For this, simply include the appropriate properties inside the Carousel tag.

 

Here's an example of how we can do this:

 
<Carousel showArrows={false} autoPlay={true} infiniteLoop={true} interval={5000}>
    {/* Carousel content */}
</Carousel>
 

showArrows={false}: This property hides the navigation arrows on the carousel, offering a cleaner interface without any directional indicators.

 

autoPlay={true}: Enabling the autoPlay feature allows the carousel to move between slides automatically, without needing any input from the user. Each slide stays visible for a set period before smoothly transitioning to the next one.

 

infiniteLoop={true}: Setting infiniteLoop to true allows the carousel to cycle continuously through its content, even after reaching the last slide. This creates a seamless viewing experience for users.

 

interval={5000}: The interval property specifies the duration, in milliseconds, between slide transitions when autoplay is enabled. In this case, each slide will be displayed for 5000 milliseconds (5 seconds) before transitioning to the next.

 

 

 

showArrows: Control the display of previous and next arrows. Default value: true.

 

showStatus: Display the current item's index. Default value: true.

 

showIndicators: Show small dots below the carousel for navigation. Default value: true.

 

showThumbs: Display thumbnails for each item in the carousel. Default value: true.

 

thumbWidth: Specify the width of thumbnails to avoid calculation issues. Default value: undefined.

 

infiniteLoop: Enable an infinite loop in the carousel for continuous scrolling. Default value: false.

 

selectedItem: Define the initially selected item.

 

axis: Set the orientation to horizontal or vertical. Default value: horizontal.

 

onChange: Execute actions when positions are updated.

 

onClickItem: Trigger actions when an item is clicked.

 

onClickThumb: Execute actions when a thumbnail is clicked.

 

stopOnHover: Pause auto-play when the mouse hovers over the carousel. Default value: true.

 

interval: Set the interval duration for auto-play. Default value: 3000 milliseconds.

 

transitionTime: Define the transition time between slides. Default value: 350 milliseconds.

 

swipeable: Enable swiping gestures for navigation. Default value: true.

 

dynamicHeight: Adjust the carousel height dynamically. It doesn't work with a vertical axis. Default value: false.

 

centerMode: Center the view with partial previous and next slides. Works with a horizontal axis only. Default value: false.

 

labels: Add labels to controls for better accessibility.

 

onSwipeStart: Execute actions when a swiping gesture begins.

 

onSwipeEnd: Execute actions when a swiping gesture ends.

 

onSwipeMove: Execute actions while a swiping gesture is in progress.

 

 

Conclusion

 

We hope you created your carousel using the steps given above. Understand and learn additional functionalities so you can improve your performance, and you can modify the carousel according to the theme of your project.

 

If you have any questions regarding this article, you can ask us with the help of the question box given below, you will get the answer as soon as possible.

Didn't find your answer? Add your question.

Share

Comments (0)

No comments yet. Be the first to comment!

About Author

Username

Vanvir Singh Devda ( vanvirsinh )

Full Stack Developer | MERN Stack

Joined On 12 Feb 2024

More from Vanvir Singh Devda

How to Upload Code to GitHub: Quick Steps and Detailed Instructions for Beginners

github

16 Sep 2024

In order to upload (push) your project to GitHub, it involves multiple steps that need to ....

How to create working responsive navbar with multilevel dropdown menu in React Js

react-js

9 Jul 2024

Have you ever found yourself stuck in the complexity of creating a working and responsive ....

Exploring What Web Developers Need to Know For The Future

web-development

17 May 2024

The entire world is experiencing a technological revolution, and web development as a crea....

 10 JavaScript String Methods You Must Know

javascript

9 May 2024

JavaScript provides several methods for manipulating strings. These include splitting stri....

How to install MongoDB on windows in 2024

mongodb

2 May 2024

MongoDB is a Database Management System based on NoSQL (Not Only SQL) and utilizes JSON-li....

JavaScript concepts for beginner web developer

javascript

9 May 2024

This tutorial is going to be very helpful specially for beginners in JavaScript. Throughou....

Popular Posts from Code Mafias

10 Fun Websites for Stress Relief and Relaxation During Coding Breaks

programming

11 Nov 2024

Top 10 fun websites for coders to relax during breaks. Recharge with interactive games, ar....

Mastering HTML: Top 12 Unique HTML Tags with Examples

html

4 May 2024

Through this article, learn those essential HTML tags that many developers do not know abo....

Top 60 Eye-Catching Button Designs Users Can’t Wait to Click - With Source Code

ui-ux

11 Oct 2024

Discover 60 eye-catching button designs with source code, crafted with HTML and CSS to enh....

How to Upload Code to GitHub: Quick Steps and Detailed Instructions for Beginners

github

16 Sep 2024

In order to upload (push) your project to GitHub, it involves multiple steps that need to ....

How to install MongoDB on windows in 2024

mongodb

2 May 2024

MongoDB is a Database Management System based on NoSQL (Not Only SQL) and utilizes JSON-li....

How to Implement Undo Functionality for Deleting Items in Your React App

react-js

28 Sep 2024

Learn how to implement undo functionality for deleting items in React. Follow a step-by-st....