How to Build a Responsive Carousel in React: A Beginner's Guide

How to Build a Responsive Carousel in React: A Beginner's Guide

Introduction

Creating engaging and interactive experiences is crucial in today's digital world. One of the most effective tools for this is a carousel. As a result, carousels have become very popular. And with React, you can create a dynamic and engaging user experience. This guide provides the step-by-step procedure for building a magnificent and responsive carousel.

A carousel is a slideshow that shows several images or data points. Carousels display information on home or landing pages. It displays a variety of visuals and text, as well as previous and next buttons. For more information on the carousel, click here.

Here are some benefits of using a carousel on your website:

  • Improved user engagement: Carousels capture visitors' attention and encourage interaction.

  • Efficient use of space: Carousels allow you to showcase many pieces of content in a single area.

  • Increased conversion rates: carousels guide visitors to specific products or services.

  • Visual appeal: Carousels add a pleasing and dynamic element to your website.

As mentioned above, carousels on your website can provide several benefits. A well-designed carousel captures visitors' attention and encourages interaction. It also optimizes space and guides clients to specific items or services.

Prerequisites

To follow along with this article, you will need the following:

  • A basic understanding of React fundamentals such as components, states, and props.

  • A code editor, preferably VS Code, or any other editor of your choice. To download VS Code, click here.

Installation Guide

The following are the steps required to set up a React project:

  1. Open your preferred terminal, such as Command Prompt, PowerShell, or Bash.

  2. Run the command npx create-react-app project-name. The name of the project should replace "project-name" in the command.

  3. Navigate to the project directory by running the command cd project-name.

  4. Open your text editor by running the command code .

  5. Finally, run the command npm start to start your development server in your browser.

Getting Started

First, navigate to the src folder and create an array of objects in your App.js file. The array of objects should contain all the needed information about the Carousel.


import image1 from "./images/pic1.jpg"
import image2 from "./images/pic2.jpg"
import image3 from "./images/pic3.jpg"
function App() {
  const users = [
    {
      name: 'First User',
      image: image1,
      id: 1
    },
    {
      name: 'Second User',
      image: image2,
      id: 2
    },
    {
      name: 'Third User',
      image: image3,
      id: 3
    }
  ]
  return (
   <main>
   </main>
  );
}
export default App;

To access the images in the App.js file, import each image from the images folder in the src folder.

The next thing is to create a components folder in your src folder and create a file name Carousel.js inside of it. Remember to start your Carousel.js file with capital letters.

Create a function in your Carousel components:


function Carousel() {
  return (
    <div>
    <div/>
  )
}
export default Carousel

Import your Carousel.js component into your App.js and map through the user's array of objects. Assign a key that will serve as a unique identifier to each user returned by the map and pass the user as a prop.


import Carousel from "./components/Carousel";
import image1 from "./images/pic1.jpg"
import image2 from "./images/pic2.jpg"
import image3 from "./images/pic3.jpg"
function App() {
  const users = [
    {
      name: 'First User',
      image: image1,
      id: 1
    },
    {
      name: 'Second User',
      image: image2,
      id: 2
    },
    {
      name: 'Third User',
      image: image3,
      id: 3
    }
  ]
  return (
   <main>
      <div>
        {users.map(user => (<Carousel key={user.id} user={user} />))}
      </div>
   </main>
  );
}
export default App;

Inside the carousel components, use the user variable passed down as a prop to render information about all users. But you have to destructure it first:


function Carousel({user}) {
  return (
    <>
        <div>
            <img src={user.image} alt="Images" />
            <p>{user.name}</p>
            <p>{user.id}</p>
        </div>
    </>
  )
}
export default Carousel

After destructuring your React component. Install React icon from Font-awesome using the command:

npm I react-icons

Import the icons into your App.js file:


import Carousel from "./components/Carousel";
import {FaChevronRight, FaChevronLeft} from "react-icons/fa"
import image1 from "./images/pic1.jpg"
import image2 from "./images/pic2.jpg"
import image3 from "./images/pic3.jpg"
function App() {
  const users = [
    {
      name: 'First User',
      image: image1,
      id: 1
    },
    {
      name: 'Second User',
      image: image2,
      id: 2
    },
    {
      name: 'Third User',
      image: image3,
      id: 3
    }
  ]
  return (
   <main>
      <div>
        <FaChevronLeft/>
        {users.map(user => (<Carousel key={user.id} user={user}/>))}
        <FaChevronRight/>
      </div>
   </main>
  );
}
export default App;

Next, import the use state and create a state hook that keeps track of and updates the value of the current user:


import Carousel from "./components/Carousel";
import { useState } from "react";
import {FaChevronRight, FaChevronLeft} from "react-icons/fa"
import image1 from "./images/pic1.jpg"
import image2 from "./images/pic2.jpg"
import image3 from "./images/pic3.jpg"
function App() {
  const users = [
    {
      name: 'First User',
      image: image1,
      id: 1
    },
    {
      name: 'Second User',
      image: image2,
      id: 2
    },
    {
      name: 'Third User',
      image: image3,
      id: 3
    }
  ]
  const [currentUser, setCurrentUser] = useState(0)
  return (
   <main>
      <div>
        <FaChevronLeft/>
        {users.map(user => (<Carousel key={user.id} user={user}/>))}
        <FaChevronRight/>
      </div>
   </main>
  );
}
export default App;

Create a function that handles clicking for both the Previous and Next buttons. Add an on-click handler to your icons:


import Carousel from "./components/Carousel";
import { useState } from "react";
import {FaChevronRight, FaChevronLeft} from "react-icons/fa"
import image1 from "./images/pic1.jpg"
import image2 from "./images/pic2.jpg"
import image3 from "./images/pic3.jpg"
function App() {
  const users = [
    {
      name: 'First User',
      image: image1,
      id: 1
    },
    {
      name: 'Second User',
      image: image2,
      id: 2
    },
    {
      name: 'Third User',
      image: image3,
      id: 3
    }
  ]
  const [currentUser, setCurrentUser] = useState(0)

  const handleNext = () => {
    currentUser === users.length - 1 ? setCurrentUser(0) : setCurrentUser(currentUser + 1)
  }
  const handlePrev = () => {
    currentUser === 0 ? setCurrentUser(users.length - 1) : setCurrentUser(currentUser - 1)
  }
  return (
   <main>
      <div>
        <FaChevronLeft onClick={handlePrev}/>
        {users.map(user => (<Carousel key={user.id} user={user}/>))}
        <FaChevronRight onClick={handleNext}/>
      </div>
   </main>
  );
}
export default App;

Next, you have to pass down the currentUser state to the Carousel component


import Carousel from "./components/Carousel";
import { useState } from "react";
import {FaChevronRight, FaChevronLeft} from "react-icons/fa"
import image1 from "./images/pic1.jpg"
import image2 from "./images/pic2.jpg"
import image3 from "./images/pic3.jpg"
function App() {
  const users = [
    {
      name: 'First User',
      image: image1,
      id: 1
    },
    {
      name: 'Second User',
      image: image2,
      id: 2
    },
    {
      name: 'Third User',
      image: image3,
      id: 3
    }
  ]
  const [currentUser, setCurrentUser] = useState(0)

  const handleNext = () => {
    currentUser === users.length - 1 ? setCurrentUser(0) : setCurrentUser(currentUser + 1)
  }
  const handlePrev = () => {
    currentUser === 0 ? setCurrentUser(users.length - 1) : setCurrentUser(currentUser - 1)
  }
  return (
   <main>
      <div>
        <FaChevronLeft onClick={handlePrev}/>
        {users.map(user => (<Carousel key={user.id} user={user} currentUser={currentUser} />))}
        <FaChevronRight onClick={handleNext}/>
      </div>
   </main>
  );
}
export default App;

Destructure the current user props in your Carousel component. Use a condition to add a class of "active" to the carousel's current user information.


function Carousel({user, currentUser}) {
  return (
    <>
        <div className={user.id - 1 === currentUser ? "carousel active" : "carousel"}>
            <img src={user.image} alt="Images" />
            <p>{user.name}</p>
            <p>{user.id}</p>
        </div>
    </>
  )
}
export default Carousel;

Styling the Carousel

To style your carousel, you need to provide a Class or Id to every element you are styling in the index.css file.


import Carousel from "./components/Carousel";
import { useState } from "react";
import {FaChevronRight, FaChevronLeft} from "react-icons/fa"
import image1 from "./images/pic1.jpg"
import image2 from "./images/pic2.jpg"
import image3 from "./images/pic3.jpg"
function App() {
  const users = [
    {
      name: 'First User',
      image: image1,
      id: 1
    },
    {
      name: 'Second User',
      image: image2,
      id: 2
    },
    {
      name: 'Third User',
      image: image3,
      id: 3
    }
  ]
  const [currentUser, setCurrentUser] = useState(0)
  const handleNext = () => {
    currentUser === users.length - 1 ? setCurrentUser(0) : setCurrentUser(currentUser + 1)
  }
  const handlePrev = () => {
    currentUser === 0 ? setCurrentUser(users.length - 1) : setCurrentUser(currentUser - 1)
  }
  return (
   <main>
      <div className="container">
        <FaChevronLeft onClick={handlePrev} className="btn"/>
        {
          users.map(user => (<Carousel key={user.id} user={user} currentUser={currentUser}/>))
        }
        <FaChevronRight onClick={handleNext} className="btn"/>
      </div>
   </main>
  );
}
export default App;

Style your element. Your styling may defer from the one provided below but make sure to style the active class to show the current user.


main{
  display: grid;
  place-items: center;
  min-height: 100vh;
}
.container {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 85%;
  max-width: 500px;
  height: 400px;
  margin: auto;
  text-align: center;
  background-color: #ab9d9d;
  color: white;
  padding: 20px;
  transition: 5ms;
}
.btn{
  z-index: 100;
}
.btn:hover{
  cursor: pointer;
}
.carousel{
  position: absolute;
  left: 0;
  right: 0;
  margin: auto;
  top: 20px;
  z-index: -1;
  width: 0;
  opacity: 0;
  transition: ease .5s;
}
.carousel.active{
  z-index: 1;
  width: 100%;
  opacity: 1;
}
.carousel img{
  width: 80%;
  aspect-ratio: 3/2.2;
}

You can add or change the information provided in the user array of objects.

The preceding animated GIF shows the carousel in action. Check out the GitHub repository here.

Conclusion

In conclusion, building a simple carousel with React can help enhance the user experience. Following this guide taught you how to create a basic carousel component. Remember, there are different ways to customize and improve your carousel. You can take your carousel component to the next level with further practice.

Hope this tutorial was helpful and that you feel inspired to continue exploring. If you have any questions, feedback, or suggestions, please feel free to comment below.

Resources

You will find the following resources helpful: