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

Create an array using modern ES6 imports syntax

I am currently in the process of transitioning Node javascript code to typescript, necessitating a shift from using require() to import. Below is the initial javascript: const stuff = [ require("./elsewhere/part1"), require("./elsew ...

Develop a dynamic animation using gradient and opacity properties

I'm still getting the hang of HTML, JavaScript, and CSS but I recently made some changes to someone else's code to animate a gradient. The original code used background: rgb, but I switched it to background: rgba. It seems to be working fine, but ...

Unable to retrieve the parent element using jQuery

I am facing an issue with my html structure that is generated dynamically through a foreach loop. I have attempted to remove the entire <a> element by accessing it from its ACTIVE HYPERLINK. However, all my efforts seem to be in vain as I am unable t ...

Error in React Native Typescript: The type 'string' cannot be assigned to the type '"solid" | "clear" | "outline"'. (Error code: ts(2322))

I have integrated TypeScript with React Native in my project. import React from 'react'; import { Button } from 'react-native-elements'; import { IThemedButton } from '../../../models/themedButton'; interface IThemedButtonPr ...

Angular 6: A guide to dynamically highlighting navbar elements based on scroll position

I am currently building a single page using Angular 6. The page is quite basic, and my goal is to emphasize the navbar based on scrolling. Below is the code snippet I am working with: .sticky { position: sticky; top: 0; } #i ul { list-style-type: ...

Having multiple Angular two applications running simultaneously within a single webpage

I have encountered an issue while trying to display two separate Calendars on a single page. The first Calendar loads successfully, but the second one does not load at all. There seems to be no attempt made to load it. As I am relatively new to Angular, I ...

Guide to creating a unique React component for displaying a single popup upon clicking with the ability to pass props to it

As someone who is still learning React, I decided to challenge myself by creating a Jeopardy game using this framework. My current idea is to have a popup appear when a player clicks on a box on the Jeopardy board, displaying the clue associated with that ...

The special function fails to execute within an "if" condition

As a newcomer to JavaScript/jQuery and Stack Overflow, I kindly ask for your patience in case there are any major errors in my approach. I am currently developing an HTML page with Bootstrap 3.3.7, featuring a pagination button group that toggles the visib ...

Using Vue.js, separate the values that are separated by commas

I am looking to extract values from a string and store them in an array for use in displaying values in a dropdown format within Vuejs String str = "abc,123,676,uuu". Once I have iterated through the values <li v-for = "value i ...

Issue encountered while attempting to start npm: Error code from NPM

I keep encountering the npm ENOENT error every time I attempt to execute npm start. I am unsure of what steps to take in order to resolve this issue. I have made efforts to adjust folder permissions. bryantcaruthers-> npm start npm ERR! code ENOENT npm ...

Error encountered in 11ty: Invalid operation - eleventyConfig.addPassthroughCopy is not a recognized function

Attempting to integrate my CSS and JavaScript codes into 11ty has been a bit challenging for me. I recently discovered that 11ty utilizes something called .11ty.js, so I decided to utilize the addPassthroughCopy() function. Below is the script I tried: mo ...

Bringing life to web pages through captivating animations when showing and hiding div elements, utilizing the power

After extensive research on various online platforms, including stackoverflow, I unfortunately couldn't find a suitable solution to my problem. However, with the invaluable assistance of you all, I managed to successfully implement a code for my proje ...

Learn how to implement drag-and-drop functionality in React by making a component

I am currently experimenting with dragging a component using the react-dnd library. I wanted to replicate functionality similar to this example, specifically only focusing on dragging at the moment. In my application, I have imported and utilized the rea ...

Get the PDF in a mobile app using HTML5 and Javascript

For my HTML5/JavaScript-based mobile application, I am in need of implementing a feature that enables users to download a PDF file. The PDF file will be provided to me as a Base64 encoded byte stream. How can I allow users to initiate the download proces ...

The REST API request returns a response code of 0

I have been attempting to make an API call to the Insightly API using this code: var x = new XMLHttpRequest(); x.open("GET", "https://api.insight.ly/v2.2/Projects/Search?status=in%20progress&brief=false&count_total=false", true); x.setRequestHeade ...

The segmented button's dropdown menu in Bootstrap is malfunctioning on Firefox version 27.0.1

I'm attempting to create a basic search bar using Bootstrap's segmented button feature (check out an example at http://getbootstrap.com/components/#input-groups-buttons-segmented). This is the code I have so far, and it's accessible on jsfi ...

Issue with MUI icon import: React, Typescript, and MUI type error - Overload does not match this call

Within my component, I am importing the following: import LogoutIcon from "@mui/icons-material/Logout"; import useLogout from "@/hooks/auth/useLogout"; const { trigger: logoutTrigger } = useLogout(); However, when utilizing this compo ...

Passing data between API tests in JavaScript

I'm encountering an issue where I need to create e2e api tests. The goal of the first test is to obtain a token for an unauthorized user, use that token in the method header for the second test to return a token for an authorized user, and then contin ...

The attempt to compress the code from this particular file within the node_modules directory was unsuccessful

Hey there! I'm facing an issue while attempting to compile my React project using npm run build. Upon running this command in the console, I encountered the following error message: Failed to minify the code from this file: ./node_modules/react- ...

"Trouble with Heroku: JavaScript script failing to load with 404

My adventure in building my first web app using MEAN on Heroku has been both thrilling and frustrating. I meticulously followed their guide to set up a sample app, downloaded the code, and made modifications to have a customized login page. However, I hit ...