Let’s Build A Beautiful Carousel From The Ground Up

Using React Spring Animations and Styled Components.

Oscar Bastos
3 min readJan 28, 2021
carousel with smooth animation

Carousels are a common sight on today’s most popular websites, such as Netflix, Amazon Prime, and Disney+. They’re often used in our own projects as well. When looking to add a carousel, we typically turn to a component library or npm package for a ready-made solution. While there are certainly some great off-the-shelf options available, there may be situations where using these libraries is overkill. For example, they could add unnecessary bulk to the project’s bundle size, or customizing them becomes a challenge, such as when trying to optimize for a page with over 40 carousels like Netflix.

Yes, you can create a carousel on your own, but first let’s delve into the mechanics of how it works and the magic behind the illusion of moving images in a browser window. The process might be simpler than you think, take a look at the image below for an example:

carousel with visible horizontal scroll bar

The secret behind creating a carousel is as simple as it sounds: It’s just a panel with a horizontal scroll bar! But the trick is to hide the scroll bar and overflow, creating the illusion that the images are smoothly sliding. To build your own carousel step by step, you can:

  1. Create a container for the carousel with overflow set to hidden.
  2. Inside this container, create a div (we’ll call it “MovingStripe”) that will be used to move left or right when the arrows are clicked.
  3. When the user clicks the arrows, we’ll use the CSS3 transform property to move the MovingStripe element 100% to the left or right, and include a transition property for a smooth animation.
  4. We’ll use the hasPrevious and hasNext functions to check if there are more cards remaining and show or hide the previous or next arrows accordingly. For a more detailed guide, please take a look at the following simple source code for an example:

This sample source code is a great starting point to show you how to create a basic carousel. But if you’re looking to create a production-ready, optimized carousel, you’ll also want to keep in mind a few other important elements, such as:

  • Making sure the carousel is properly displayed on different devices like mobile phones, tablets and desktops.
  • Optimizing performance when the carousel contains a lot of elements by using windowing techniques on the carousel’s dataset.
  • Paying attention to the styling of the components to create an attractive and polished look.
  • Adding unit tests to ensure reliability.

I hope this explanation has provided you with a deeper understanding of how to create a carousel.

--

--