With this article I am going to show you how you can create your own Carousel component using React that supports multiple items and server-side rendering and add testing to it and finally publish to NPM.
This is part one of the series "React Carousel with Server Side Rendering Support". Part two can be found at w3js.
If you prefer to jump right to the code, i have made two versions of the Carousel, first version is the one we will be building in this tutorial with basic usage and the bare minimal amount of code that's easier for you to understand and beginner friendly. For the second version, it is made as a npm package which is an improved version of the first one with more advanced usage.
One of the most common ways to building a Carousel component is to calculate the entire width of the Carousel component and divided by the amount of items you want to show will eventually be the average width of item inside the Carousel. After all the items are rendered nicely, the navigation are usually done by changing the "transform" property of the Carousel container with either "translateX" or "translate3d" with some math calculations as the following code snippets:
const itemsToShow = 4; const containerWidth = document.getElementById("#container").offsetWidth; const itemWidth = containerWidth / 4; <Carousel> <item1 style="width=itemWidth" /> <item2 style="width=itemWidth" /> <item3 style="width=itemWidth" /> </Carousel>
Here is the approach that we will be using, don't worry if you don't completely understand, but you will learn about it more once we get to the implementation step by step later.
const itemsToShowWhenOnServerSide = 3; <CarouselItem style="flex-basis=33%" />
For our next post part two, we will be diving into the implementation with code.
Interested to see how to show case React components in storybook as your project's documentation? Follow my next article which is coming soon.