Carousel React Component: Creating an Instagram-Like Slider
In this tutorial, we will walk through the process of creating a carousel React Component that mimics the functionality of Instagram’s carousel feature. A carousel is a popular UI pattern that allows users to scroll through a series of images or content horizontally. We will leverage React and CSS to build our Instagram-like carousel.
The whole code is available in github.
Table of Content:
Prerequisites:
To follow along with this tutorial, you should have a basic understanding of React and JavaScript. Make sure you have NodeJs, npm (Node Package Manager), react installed on your machine.
Install react package using npm by executing the below command in terminal.
npm install -g create-react-app
Setting Up the Project:
Let’s start by setting up a new React project. Open your terminal and execute the following commands:
npx create-react-app carousel-react-component
cd carousel-react-component
This will create a new React project called “carousel-react-component” and navigate you into its directory. The project structure should look like as below.
Creating the Carousel Component:
Next, let’s create a new file called Carousel.js
in the src
directory. Open the file and add the following code:
import React, { useState } from 'react';
import './Carousel.css';
const Carousel = ({ images }) => {
const [currentIndex, setCurrentIndex] = useState(0);
const nextSlide = () => {
setCurrentIndex((prevIndex) => (prevIndex + 1) % images.length);
};
const prevSlide = () => {
setCurrentIndex((prevIndex) =>
prevIndex === 0 ? images.length - 1 : prevIndex - 1
);
};
return (
<div className="carousel">
<div
className="carousel-inner"
style={{
transform: `translateX(-${currentIndex * 100}%)`,
}}
>
{images.map((image, index) => (
<div key={index} className="slide">
<img src={image} alt={`Image ${index}`} />
</div>
))}
</div>
<button className="prev-button" onClick={prevSlide}>
Prev
</button>
<button className="next-button" onClick={nextSlide}>
Next
</button>
</div>
);
};
export default Carousel;
Let’s create a new file called Carousel.css
in the src
directory and add the below code.
.carousel {
position: relative;
width: 100%;
height: 400px;
overflow: hidden;
}
.carousel-inner {
display: flex;
transition: transform 0.3s ease-in-out;
}
.slide {
flex: 0 0 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
}
.slide img {
max-width: 100%;
max-height: 100%;
}
.prev-button,
.next-button {
position: absolute;
top: 50%;
transform: translateY(-50%);
background-color: #fff;
border: none;
padding: 10px;
font-size: 18px;
cursor: pointer;
z-index: 1;
}
.prev-button {
left: 10px;
}
.next-button {
right: 10px;
}
Lets understand what is happening in Carousel.js
- We used
useState
hook from the ‘react’ package that allows us to manage state within a functional component. - We had created and imported the CSS file
Carousel.css
that apply custom styles to our carousel. - The
Carousel
component is defined as a functional component that receives animages
prop representing an array of image URLs. - Inside the component, we use the
useState
hook to define thecurrentIndex
state variable, initialized with a value of 0.setCurrentIndex
is a function that allows us to update the value ofcurrentIndex
. - We define two helper functions,
nextSlide
andprevSlide
, to handle moving to the next and previous slides respectively.nextSlide
increments thecurrentIndex
by 1, andprevSlide
decrements thecurrentIndex
by 1, considering the boundaries of theimages
array. - In the JSX markup, we render the carousel component. It consists of a main
div
with the class namecarousel
. - Inside the main
div
, we have a nesteddiv
with the class namecarousel-inner
. We apply an inline style to this div using thetransform
property to slide the carousel horizontally based on the value ofcurrentIndex
. The translation is achieved by multiplyingcurrentIndex
with -100%. - Within the
carousel-inner
div, we map over theimages
array and render each image within adiv
with the class nameslide
. The image URLs are set as thesrc
attribute of theimg
element. Analt
attribute is provided with the format “Image {index}” for accessibility. - Lastly, we add two buttons, one with the class name
prev-button
and the other with the class namenext-button
. These buttons trigger theprevSlide
andnextSlide
functions respectively when clicked. - Finally, we export the
Carousel
component to be used in other parts of the application.
Integrating the Carousel:
Now, let’s integrate our Carousel
component into the root component of our React application. Open the src/App.js
file and replace its content with the following code: To test we had used images from picsum.photos which provides mock images.
import React from 'react';
import Carousel from './Carousel';
import './Carousel.css';
const App = () => {
const images = [
'https://fastly.picsum.photos/id/125/200/300.jpg?hmac=yLvRBwUcr6LYWuGaGk05UjiU5vArBo3Idr3ap5tpSxU',
'https://fastly.picsum.photos/id/362/200/300.jpg?hmac=YjZiJWaqrdKL4xFhgrjDw4Ic2tPzNLV975FWRb8td0s',
'https://fastly.picsum.photos/id/542/200/300.jpg?hmac=qD8M4ejDPlEc69pGT21BzB7CDiWOcElb_Ke7V8POjm8',
];
return (
<div className="App">
<h1>Instagram-Like Carousel</h1>
<Carousel images={images} />
</div>
);
};
export default App;
This code imports our Carousel
and renders it within the root component. Additionally, it adds a simple heading to demonstrate the usage of the carousel.
Running the Application:
We are now ready to test our Instagram-like carousel react component. In the project directory, run the following command to start the development server:
npm start
Open your web browser and navigate to http://localhost:3000
. You should see the title “Instagram-Like Carousel React Component” and the carousel with the images we provided. Try scrolling through the carousel to see the images sliding horizontally.
In this tutorial, we have built an Instagram-like carousel React component that allows users to scroll through a series of images horizontally. You can extend this component with additional features and customize it further to create a more advanced and visually appealing carousel.
Explore this article to discover the process of developing an npm package for ChatGPT, enabling you to create and distribute custom chatbot functionalities.
7 Responses