Creating a Carousel With Horizontal Scrolling Using React
In a recent front-end project, I found myself pouring hours into the implementation of a carousel that could be traversed using directional buttons and standard horizontal scrolling.
My initial approach involved translating the carousel (henceforth referred to as The Slider) via CSS in-line styling. I would create a reference to the slider, and use that reference to capture the total width (in pixels) of the scroll area. The in-line styling would then be applied based on the current width of the slider, translating by -960 pixels on button click in order to get move to the next four items in my carousel.
This approach proved to be too complicated for my liking, as I would need to find a way to allow for scrolling to track the positive value of the remaining width of the carousel, while also using the same positive number to apply a negative value to the translation in the inline styling.
Ultimately, I opted for a more direct approach: keep the reference to the slider, and use the scrollTo method on button click to move the slider to the left or right by a set amount of pixels. If the scroll bar was within a certain range of the beginning or end of the slider when a directional button was clicked, it would simply move to the start or stopping point, respectively.
Here’s what my code looked like:
There you have it! I hope this saved you time and frustration.