Develop a circular carousel using React JS from scratch, without relying on any third-party library

I am looking to replicate the carousel feature seen on this website. I want to mimic the same functionality without relying on any external libraries. I have found several resources explaining how to achieve this. Most suggest creating duplicate copies of the carousel track and switching between them, but I prefer not to do that. The code below works well when sliding within the boundary elements (1st and last slide). How can I smoothly transition from the last slide to the first slide and vice versa? Adjusting the left offset can move me from the last back to the first slide, but it doesn't give the carousel an infinite looping effect. Is appending the first slide after the last one the only solution to achieve this?

import {useRef, useEffect} from "react";
import {details} from "./constants";

const App = () => {
  const carousel_track = useRef();
  const container = useRef();
  let counter = 0;
  const card = useRef();
  const prevSlide = () => {
    const width = card.current.offsetWidth;
    counter--;
    carousel_track.current.style.left = -width * counter + "px";
  };
  const nextSlide = () => {
    const width = card.current.offsetWidth;
    counter++;
    carousel_track.current.style.left = -width * counter + "px";
  };
  useEffect(() => {
    addEventListener("keydown", (e) => {
      if (e.code === "ArrowRight") nextSlide();
      if (e.code === "ArrowLeft") prevSlide();
    });
  }, []);

  return (
    <div className="w-screen h-screen flex items-center bg-slate-500">
      <div
        ref={container}
        className="w-screen h-2/3 transition-all overflow-x-hidden relative border-cyan-800 border-4"
      >
        <div
          onClick={prevSlide}
          className="absolute cursor-pointer text-2xl text-white z-10 left-0 top-1/2"
        >
          Prev
        </div>
        <div
          onClick={nextSlide}
          className="absolute cursor-pointer text-2xl text-white z-10 right-0 top-1/2"
        >
          Next
        </div>
        <div
          ref={carousel_track}
          className="w-[200%] h-full flex transition-all justify-start items-center absolute bg-red-800"
        >
          {details.map((slide) => (
            <div
              ref={card}
              className="w-screen h-full flex-shrink-0"
              key={slide.title}
            >
              <div className="rounded-lg h-full">
                <img
                  src={slide.image}
                  alt="image"
                  className="rounded-lg w-full h-full object-cover"
                />
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

export default App;

Answer №1

Here is a simple implementation of a circular carousel in React, created without relying on any external libraries.

import React, { useState } from 'react';

const Carousel = ({ images }) => {
  const [currentIndex, setCurrentIndex] = useState(0);

.
.
.

export default App;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with changing the opacity of a Javascript button style is not functioning correctly

The button's opacity used to change gradually in increments of 0.1 every 500 milliseconds, but now it instantly changes to 0.9 without the delay. Issue: Despite being placed within a window load handler and all elements loading properly, the loop is ...

A comparison between Buffer.byteLength and file size

I'm facing an issue with file size discrepancies. I have a file that is reported as 51Mb in Finder, but when uploaded to the server, the byteLength of the Buffer shows a much smaller size. Could this difference be due to the file type or other propert ...

Supporting server-side routing with NodeJS and Express for AngularJS applications

My current setup includes NodeJS + expressJS on the server and AngularJS on the client side. The routes defined in my AngularJS controller are as follows: app.config(function($routeProvider,$locationProvider) { $routeProvider .when('/field1/:id&apo ...

Prevent Mui popover from closing when clicking outside

Currently, I have implemented Mui Popover with ReactJS from the link here. One issue I am facing is that when a user clicks outside the popover, it automatically closes. Is there a way to disable this default behavior? Additionally, I would like to add a ...

What steps can be taken to resolve webpage loading issues following data insertion into a database using express and node?

My express app has a post route handler (/addpost) for adding data to a database. Everything works perfectly, but the window keeps loading. To prevent the browser from waiting for more data, I know I need to send a response. However, all I want is for th ...

The useRef value is not defined when used inside the useEffect function

I'm confused about the behavior of useEffect. The documentation says it runs after HTML elements are rendered, so why am I getting an undefined value for the useRef hook inside the useEffect function? How can I use useEffect to set the value of an Inp ...

Struggling to connect API from React and Node using a proxy server

I have encountered a troubleshooting issue with React and Node that I am struggling to resolve. The problem lies in the communication between my node server and coinmarketcap API. While I successfully receive data from both endpoints (all coins and individ ...

Attempting to deactivate expired cards

Hello everyone, I could really use some assistance. I am trying to map items with a specific property called 'expired' and I want each card to render in a disabled state. However, I'm struggling to achieve this using MUI components. Here is ...

Tips for extracting information from a website with Selenium using Python

I am currently working on a project that requires me to extract certain information using Selenium from a webpage. The elements I need are not directly visible in the page's code, indicating they may be generated by JavaScript. Here is a snippet of my ...

Running the JavaScript function prior to its interval being triggered

I'm in the process of developing a PHP dashboard page with various features, but there's one particular issue that bothers me, although it's not too major. The problem I'm facing is that I have a JavaScript function that fetches data a ...

Bootstrap 5 does not support tab navigation functionality

I created a new HTML page, and I encountered an issue while trying to enable tabs using JavaScript. <html> <head> <title>Excel Viewer</title> <link hr ...

The UNHANDLEDREJECTION callback was triggered prematurely during asynchronous parallel execution

Asynchronously using parallel to retrieve data from the database in parallel. Upon each task returning the data, it is stored in a local object. In index.js, the cacheService.js is called. Inside cacheService.js, data is loaded from both MySQL and MongoDB ...

Tips for stopping the entire webpage from scrolling in Vuetify

Hey there, I'm facing an issue with scrolling on mobile devices and iPads. When I view my site on desktop, there is no scrolling behavior, but as soon as I switch to a mobile device or iPad, the scroll appears. This problem is specific to mobile devic ...

Ways to remove a

After creating an npm link within a local dependency and then deleting that dependency from my hard drive, I am now attempting to remove this npm link. I have attempted the following steps: npm rm --global dependency npm uninstall dependency npm unlink - ...

A custom Mongoose schema attribute configured with distinct values

I've been working on some code and here is what I have: var userSchema = new mongoose.Schema({ email: String, password: String, role: Something }); I'm aiming to set specific values ('admin', 'member', 'guest&apos ...

Watching a specific property amongst various objects using VueJS deep watcher

Issue at Hand In my scenario, I have an array named "products" that consists of multiple objects. Each object within the product array includes a property called "price". My goal is to monitor any changes in this particular property for each product. This ...

Animating CSS styles in Vue.js based on JavaScript triggers

Within my Vue.js application, I've implemented a login form that I'd like to shake whenever a login attempt fails. Though I have achieved the desired shaking effect, I'm not completely satisfied with my current solution. Here's a simpl ...

[NextJS]: Sending a collection of companies from a server to a client-side component

Scenario: My server component retrieves a list of organizations and sends it to a client component. The client component sets the organizations state based on the received data and performs operations on it, such as changing an organization's status f ...

Sending images as a base64 string from a Titanium app to a Ruby on Rails web service

I am encountering an issue when trying to upload an image from an app that has been converted into a base64 string to a Ruby on Rails server. The app is developed using Titanium. However, after retrieving and decoding the image string back into an image, ...

What is the best way to toggle between a login and signup form using an anchor tag in a React application?

As a newcomer to the world of React and web development, I found myself challenged with a task. I needed to create a code that would allow users to switch between a login form and a signup form in React. The idea was that clicking on the Don't have an ...