One of the most attractive features that you can add to your website or application is using a carousel or image slider. A carousel allows the user to view several images or items in a scrollable manner and see more content. However, creating attractive and user-friendly carousels requires familiarity with advanced techniques such as showing detailed next and previous images.
Here, I want to create a carousel using the beloved React library that will display images next and previous in a detailed manner. The aim of this task is to attract more user engagement and provide a better user experience.
To start, we'll create a new React project and include the React library. Then, we will use CSS, which is necessary to design classes that will showcase some of the most prominent templates of carousels. Likewise, by using JavaScript capabilities, we will dynamically add images to this carousel so that images can be properly displayed.
I would like to include part of the sample code for creating such a carousel. The code includes the use of refs and states in React for transitioning between images and managing the status of the carousel.
import React, { useRef, useState } from 'react';
import './Carousel.css';
const Carousel = ({ items }) => {
const [currentIndex, setCurrentIndex] = useState(0);
const ref = useRef(null);
const handleNext = () => {
setCurrentIndex((prevIndex) => (prevIndex + 1) % items.length);
};
const handlePrev = () => {
setCurrentIndex((prevIndex) => (prevIndex - 1 + items.length) % items.length);
};
return (
{items.map((item, idx) => (
{item}
))}
);
};
export default Carousel;
Code Explanation Line by Line:
import React, { useRef, useState } from 'react';
First of all, we have imported the React components necessary for creating states and referring to DOM elements.
const Carousel = ({ items }) => {
Here, we define a functional component that takes an array of items as a prop.
const [currentIndex, setCurrentIndex] = useState(0);
We define a state for displaying the current item starting from an initial value of 0.
const ref = useRef(null);
This creates a ref for accessing the DOM element of the carousel.
const handleNext = () => { ... }
A function that updates the index for viewing the next image.
const handlePrev = () => { ... }
A function that updates the index for viewing the previous image.
<div className="carousel-container" ref={ref}>
This is a container div that includes all the content of the carousel and is used as the primary element.
<button onClick={handlePrev}>Prev</button>
A button for viewing the previous image.
<div className="carousel-content">...
This div contains the items of the carousel and moves via CSS.
style={{ transform: `translateX(-${currentIndex * 100}%)` }}
This property is used for moving the content of the carousel based on the current index.
<button onClick={handleNext}>Next</button>
A button for viewing the next image.