Creating a Carousel in React
Utilising React, Hooks, TypeScript and Styled Components.
I recently had the task of implementing a Carousel for a project at work. Initially, the plan was to use a pre-existing library to quickly scaffold the carousel and add our images and copy and then move on to the next task.
It quickly became apparent however, that not only would we require the ‘bloat’ from the package installation itself, but we’d need roughly 300 lines of CSS too, given that we didn’t want to directly import any themes due to our Content Security Policy (see more here).
Additionally, it also started proving quite difficult to implement some custom designs we had mocked up for the left/right scrolling arrows.
As such, after consulting with the team, the decision was made to go ahead and try and create a custom carousel. Here’s how I did it, with far less code and more control over the component.
The Basics
First we need the content for our slides. First, I created a Carousel
component which will contain several children
. These will be our individual slide components that will be passed as JSX elements.
Each individual component looks like so:
Now to import the Carousel.tsx
to App.tsx
and pass through those child components. NB: The reason we decided to design the Carousel this way was so that if we ever needed to use it elsewhere (which eventually we did) we could just call our Carousel
component again and pass in different slides as children.
The result will look something like this:
Not really what we want, but this is good progress. We wanted our carousel to have various features, but for the sake of this post, I’ll cover some basics which we’ll quickly scaffold:
- We only want to display the active slide at any one time. We can achieve this by tweaking opacity settings on the slides depending on whether they are active or not.
- We’ll need two buttons to navigate left and right between the slides. It should also feature continuous scrolling. We can achieve this using a modulus.
Opacity:
Scrolling Logic:
The final code for the Carousel:
You should now have the scaffolding for a Carousel without needing to add further dependencies and the added flexibility of using your own styling methods. You may choose to replace the buttons with custom icons you might have or alternatively employ setInterval()
to automate the scroll every x
seconds.
Special thanks to Anthony Panagi, Fred Rivett and Phil Jones for their contributions to the original code and subsequent blog.