attempting to showcase a set of 4 cards simultaneously within a single carousel interface

I've encountered an issue while trying to create a slider for my card component. Despite several attempts, I'm struggling to display them properly.

Adjusting the width of Carousel inner from 100% to 25% resulted in an increased number of pages in the carousel, leading to blank pages once the data from my API is depleted. I aim to iterate through the API data seamlessly without encountering additional empty pages at the end of the carousel.

You can access the codesandbox link for reference here

Answer №1

To create a loop in the carousel, you can reset the active index back to 0. To achieve this, the updateIndex function needs to be modified as follows:

const updateIndex = (newIndex) =>{
        if (newIndex < 0 || newIndex >= React.Children.count(children)) {
            newIndex = 0;
        } 
        setActiveIndex(newIndex);
    };

Carousel.js

import React, { useState } from "react";
import "./Carousel.css";

export const CarouselItem = ({ children, width }) => {
  return (
    <div className="carousel-item" style={{ width: width }}>
      {children}
    </div>
  );
};

const Carousel = ({ children }) => {
  const [activeIndex, setActiveIndex] = useState(0);

  const updateIndex = (newIndex) => {
    if (newIndex < 0 || newIndex >= React.Children.count(children)) {
      newIndex = 0;
    }
    setActiveIndex(newIndex);
  };

  return (
    <>
      <div className="carousel">
        <div
          className="inner"
          style={{ transform: `translateX(-${activeIndex * 100}%)` }}
        >
          {React.Children.map(children, (child, index) => {
            return React.cloneElement(child, { width: "100%" });
          })}
        </div>
      </div>
      <div className="indicators">
        <button
          onClick={() => {
            updateIndex(activeIndex - 1);
          }}
        >
          Prev
        </button>
        {React.Children.map(children, (child, index) => {
          return (
            <button
              onClick={() => {
                updateIndex(index);
              }}
            ></button>
          );
        })}
        <button
          onClick={() => {
            updateIndex(activeIndex + 1);
          }}
        >
          Next
        </button>
      </div>
    </>
  );
};

export default Carousel;

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

The script titled "begin" is nowhere to be found within the nest

After setting up NestJS, I attempted to run it in VSCode as instructed in the documentation. The command that I used was: npm run start However, I encountered an error stating that the script "start" was missing. According to the documentation, running th ...

A Guide on Modifying a Pseudo Element When Clicked

How can I create a click handler in jQuery to change the color of an 'eyebrow' element above a Heading element? The eyebrow element is set up with a pseudo element in my project, and I'm struggling to make it change color when the heading is ...

Troubleshooting WebSocket handshake error in React and Express server running locally

I am facing an issue with setting up a WebSocket connection using socket.io on my localhost. My backend is built on express and the frontend uses React. Every time I try to establish a connection, I encounter the following error message: WebSocket connect ...

Tips for adjusting the size of a CSS radio button while ensuring the text remains centered

Uncertain about which part to modify in this radio button code to decrease its size while keeping the text aligned with the inner button. Changes made have shifted the text to the top of the button instead. Can you provide guidance on the necessary adjustm ...

Shared codes are compatible with both C and Javascript programming languages

Within the scope of this project, data will be retrieved from the server in either JSON or XML format. There are two separate client applications that will handle the data processing, with one being web-based and written in JavaScript, while the other is ...

Steps for creating a dropdown menu that opens when hovering over a selection using Bootstrap Vue

Is there a way to activate the <select> or <b-form-select> dropdown menu when hovering over it, without relying on JQuery or any third-party plugin except for Vue.js? ...

How to make an HTML element draggable without the need for an ID

I am currently working on making dynamically created divs draggable. While I have successfully achieved this with pre-existing div elements as shown below: <div> This can be dragged around, but outputs cannot?! </div> the issue arises when ...

Displaying the countdown of days and hours until a specific date is just a matter of using

Currently, I am tackling a project that necessitates a specific text response related to a date object. "1 day 7 hours away" --- This format is crucial; alternatives such as "31 hours away" or "1 day away" will not suffice. -- For language switching purpo ...

Can you explain the distinction between HashRouter and BrowserRouter within React?

Learning programming can be a challenge, especially when trying to decipher official documentation. I recently came across an article discussing the differences between React Router 4 The author delves into the differences between <HashRouter> and ...

The 'xxx' type is lacking various properties compared to the 'xxx[]' type, such as length, pop, push, concat, and many others

Utilizing typescript and reactjs, the issue lies within this component import type { InputProps } from "../utils/types" const Input = (props: InputProps) => { const makeChildren = () => { return ( <> ...

Creating a function in AngularJS to select all checkboxes

I recently started working with Angular and I implemented a select all checkbox that checks all the boxes using ng-model/ng-checked. <th> <input type="checkbox" id="selectAll" ng-model="selectAll"/> </th> <th ...

Attempting to employ the HTML5 file picker feature within the AppMaker platform

Hey there, I'm currently working on integrating the HTML5 file picker into my AppMaker app. (Since my app needs to run as the developer, I can't use Drive Picker). I've been able to display the file picker in an HTML widget using the follow ...

What causes the footer element to shift outside of the paragraph tag?

When viewing this FIDDLE, you may notice that the <footer> tag appears outside of the <p> tag despite being placed inside it in the HTML. What could be causing this unexpected behavior? HTML Code: <p>Lorem ipsum dolor sit amet, consect ...

Getting the value of a repeater label in JavaScript can be achieved by following these

Here is my javascript code: function btnEditClick() { alert(document.getElementById('<%=LblRefPhyID.ClientID %>').value); } <asp:Repeater ID="repeaterRefPhysicianList" runat="server"> <ItemTemplate> < ...

Angular 6 component experiencing issues with animation functionality

I've implemented a Notification feature using a Notification component that displays notifications at the top of the screen. The goal is to make these notifications fade in and out smoothly. In my NotificationService, there's an array that holds ...

developing a deferred commitment by utilizing promise objects

Hi everyone, I've encountered an issue with a JavaScript promise question that's throwing errors function delay(n) { return new Promise((resolve) => setTimeout(resolve, n*1000)); } The expected output should be "It is now 2 seconds later" ...

Patience is key when waiting for both subscriptions to be completed before proceeding with an

I am facing a challenge with two subscriptions as shown below: this.birthdays = await this.birthdaySP.getBirthdays(); this.birthdays.subscribe(groups => { const allBirthdayT = []; groups.map(c => { allBirthdayT.push({ key: c.pa ...

During development, react-app-rewired does not compile all files

Running the "react-app-rewired start" command in development mode results in a successful compilation of the project without any errors. However, when editing any file within /src/*, the project is recompiled but fails to respond to changes made within /s ...

Is it possible for Angular2 to map a lone JSON object?

Dealing with a JSON response that is a single object, rather than an array, can be tricky. Recently in my project, I encountered a situation where I needed to map and use such a response from an API to fill out a template. It seemed like a simple task at f ...

Slick Slider isn't compatible with Bootstrap Tab functionality

I'm having an issue with using slick slider within a Bootstrap tab menu. The first tab displays the slick slider correctly, but when I switch to the second tab, only one image is shown. How can I resolve this problem? <!DOCTYPE html> <html ...