Building an Achievements Carousel with React
Create an infinite scrolling carousel of images with a text-overlay.
Carousels are a common feature on many websites, offering a dynamic way to showcase content. Today, we'll walk through building an achievements carousel using React and TypeScript, with smooth animations and optimized image handling, thanks to libraries like framer-motion, react-use-measure, and next/image.
Creating the Component
The AchievementsCarousel function is at the core of our carousel. It keeps track of the currently hovered achievement using the hoveredIndex
state variable and accurately measures elements using the useMeasure
hook.
We use the useEffect
hook to handle the carousel's animation. By calculating the final position and animating it with framer-motion's animate
function, we create a seamless gliding effect that loops indefinitely.
Interactivity
Each achievement is wrapped in a motion.div element, allowing it to respond to hover events. As achievements are hovered over, the hoveredIndex
state updates, smoothly guiding the carousel's movement.
Inside each achievement, an AnimatePresence
component manages the appearance and disappearance of achievement details. When an achievement is hovered over, its title fades in; when it's not, it fades out.
Displaying Achievements
The next/image component takes care of displaying achievement images. With props like fill
for scaling and sizes
for responsiveness, images are presented in their best light across different screen sizes.
Styling for Impact
Now, let's delve into the CSS magic that enhances our carousel's visual appeal. Take a look at this line of code:
Here, we apply a series of CSS classes to the Card component, utilizing Tailwind CSS's utility classes. The max-w-full
ensures the card fills its container, while h-[300px]
sets a fixed height of 300 pixels. The border-none
class removes any border, and overflow-hidden
ensures that any content overflowing the card is hidden.
However, the real star of the show is the mask-image
property. By using a linear gradient, we create a striking visual effect where the edges of the card fade to black, drawing focus to the carousel's contents while adding a touch of elegance.
Conclusion
With React, TypeScript, and a few handy libraries, building an achievements carousel becomes a straightforward task. By combining functionality with smooth animations and optimized image handling, you can create a carousel that effectively showcases your content without fuss.
you go coding queen