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:

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

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.

carousel react 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

  1. We used useState hook from the ‘react’ package that allows us to manage state within a functional component.
  2. We had created and imported the CSS file Carousel.css that apply custom styles to our carousel.
  3. The Carousel component is defined as a functional component that receives an images prop representing an array of image URLs.
  4. Inside the component, we use the useState hook to define the currentIndex state variable, initialized with a value of 0. setCurrentIndex is a function that allows us to update the value of currentIndex.
  5. We define two helper functions, nextSlide and prevSlide, to handle moving to the next and previous slides respectively. nextSlide increments the currentIndex by 1, and prevSlide decrements the currentIndex by 1, considering the boundaries of the images array.
  6. In the JSX markup, we render the carousel component. It consists of a main div with the class name carousel.
  7. Inside the main div, we have a nested div with the class name carousel-inner. We apply an inline style to this div using the transform property to slide the carousel horizontally based on the value of currentIndex. The translation is achieved by multiplying currentIndex with -100%.
  8. Within the carousel-inner div, we map over the images array and render each image within a div with the class name slide. The image URLs are set as the src attribute of the img element. An alt attribute is provided with the format “Image {index}” for accessibility.
  9. Lastly, we add two buttons, one with the class name prev-button and the other with the class name next-button. These buttons trigger the prevSlide and nextSlide functions respectively when clicked.
  10. Finally, we export the Carousel component to be used in other parts of the application.

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.

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

Leave a Reply

Your email address will not be published. Required fields are marked *

Post comment