Customizing a carousel in Next JS to loop through items and control their visibility

I've created a custom Next JS carousel that tracks the current slide index and displays an image or video accordingly. However, it appears that because the carousel is set to autoplay and each slide is removed and readded every 6 seconds, the page downloads duplicate copies of the same media when they cycle back around. Is this the correct approach?

The crux of the issue lies here

{slides.map((item, key) => (
    <>
    {key == this.state.currentImageIndex && (
        <div>

It continuously removes and adds content for each slide. Could this be wasting resources by constantly downloading them? Is there a more efficient way to handle this?

import React from 'react'

//Importing data for the slides
import { slides } from './data/slides'
import VideoSlide from './VideoSlide'
import ImageSlide from './ImageSlide'

let slideTimer = null

class Carousel extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      currentImageIndex: 0, //Index of slide in /data/slides
      slideTime: 6, //Duration of each slide in seconds
    }
    this.setMyInterval = this.setMyInterval.bind(this)
  }

  //Initial setup when component mounts
  componentDidMount() {
    this.setMyInterval()
  }

  changeSlide(current) {
    /*Avoid running if selecting same slide number*/
    if (current != this.state.currentImageIndex) {
      this.setState({ currentImageIndex: current }) //Change to selected slide
      clearTimeout(slideTimer) //Reset timer
      this.setMyInterval() //Rebuild the countdown
    }
  }

  setMyInterval() {
    slideTimer = setInterval(() => {
      const lastIndex = slides.length - 1
      const { currentImageIndex } = this.state
      const shouldResetIndex = currentImageIndex === lastIndex
      const index = shouldResetIndex ? 0 : currentImageIndex + 1

      this.setState({
        currentImageIndex: index,
      })
    }, this.state.slideTime * 1000)
  }

  componentWillUnmount() {
    clearInterval(slideTimer)
  }

  render() {
    return (
      <>
        <div className="backgroundSlide">
          {slides.map((item, key) => (
            <>
              {key == this.state.currentImageIndex && (
                <div>
                  <VideoSlide url={slides[0].video} />
                  {slides[this.state.currentImageIndex].image && (
                    <ImageSlide
                      url={slides[this.state.currentImageIndex].image}
                      timer={this.state.slideTime}
                    />
                  )}
                </div>
              )}
            </>
          ))}
        </div>
      </>
    )
  }
}

export default Carousel

Answer №1

The question lacks clarity on the specific Carousel logic being used. Typically, carousel elements are rendered in full before allowing the carousel to function as intended. For instance, take a look at this CSS-only carousel example:

https://css-tricks.com/css-only-carousel/

By adopting such an approach, all slides can be rendered simultaneously, eliminating concerns about slide removal or addition during operation.

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

JavaScript condensed into a single table cell rather than occupying an entire webpage

Hey there, I have a simple question that I can't seem to find the answer to anywhere. I'm working on a JavaScript function that pulls data from my database and I want it to display in one cell of a table instead of outputting to the entire page. ...

Overriding Methods in a Node Module

I have been utilizing the keystone node module to create cms-based pages in my application. To initialize Keystone, I simply add it to my JavaScript file like this: var keystone = require('keystone'); The issue I am currently facing is that th ...

Securing user access and storing authentication tokens in NextJS

Currently utilizing NextJS for Server-side Rendering Our authentication method involves the use of JWT In a standard React application, we can employ JWT for each server request to retrieve data However, some pages return varied data based on whether th ...

Tips for integrating SQL queries into a document that consists mostly of JavaScript and JQuery

I am currently in the process of integrating a SQL database write into my file that is primarily comprised of JavaScript and jQuery. While I have come across some PHP resources online, I am facing challenges incorporating the PHP code into my existing scri ...

What is the best way to programmatically select a checkbox that was created dynamically using jQuery?

I've been scouring the internet trying to find information on what I'm attempting to accomplish, but so far I haven't come across anything helpful. The issue I'm facing is with a form that has a section dynamically added using JavaScri ...

I am looking to incorporate a password recovery page into my login process, but I am facing difficulty navigating to it once the code has been modified

I'm looking to include a forgotten password option on my login page, but I'm facing an issue when trying to navigate to it after updating the code. The website is throwing the following error message: [vue-router] uncaught error during rout ...

Is it possible for a Vue data property to have a value that is determined by another Vue data property object?

Within my HTML form, I have implemented the flatPickr (calendar picker) component which generates an input field. I am currently exploring how to dynamically change the class of the input field if the error class function returns true. Below is the flatPi ...

What is the best approach for managing multiple HTTP requests in my specific situation?

I have a query about handling multiple HTTP requests in my code to ultimately get the desired result. Here is an outline of my approach: var customer[]; var url = '/api/project/getCustomer'; getProject(url) .then(function(data){ ...

Conceal navigation buttons on the first and last pages of the slider

I'm attempting to develop a slider that hides the "previous" button when it is on the first slide and hides the "next" button when it reaches the last slide. The slider will be created using a combination of PHP, forms, and JavaScript. Below is the H ...

Unexpected TypeError thrown by a simple react-cube-navigation demonstration

Looking to utilize the react-cube-navigation component, available here. Encountering a TypeError when attempting to run the provided example, React throws an error: TypeError: props.rotateY.to(function (x) { return "scale is not a function. ( ...

Obtain the index of the selected item from a dropdown menu

Is there a way for the selectedIndex to return -1 if no item is selected, instead of the element's text at position 0? It seems that the selectedIndex always returns 0 even when nothing is selected. <select id="abc" name="abc"> <option& ...

The try/catch block fails to execute or capture any errors

I'm attempting to create a help command that notifies users in case of closed DMs, but it's not working as expected. Despite encountering an error, the original messages are still sent instead of executing the catch function. I am relatively new ...

Configuring the IntelliJ debugger to allow for breaking inside or stepping through an NPM script

I am utilizing an NPM script that executes and produces a file within the repository. Could you please guide me on setting up the debugger to run the script in a way that allows me to perform actions like breaking inside of it and stepping through its cod ...

React native and redux: Updating state with setState is not possible during an ongoing state transition

Currently in the process of developing an app utilizing React Native and redux, alongside Express js for handling Ajax requests. Encountering an issue where the data from my Ajax request fails to load, accompanied by the following warning: Warning: set ...

Tips for obtaining validation errors on input elements in React when the input field is of type "file"

Currently, I am utilizing Material UI to cover the input component with icons. However, I have encountered an issue where there is an input element hidden and as a result, validation errors are not being displayed. The library I am using for validation i ...

What steps can be taken to repair the script?

https://jsfiddle.net/fnethLxm/10/ $(document).ready(function() { parallaxAuto() }); function parallaxAuto() { var viewer = document.querySelector('.viewer.active'), frame_count = 5, offset_value = 500; // init control ...

Click on the marker to adjust the map's central position

I've successfully created a leaflet map featuring an array of 3 different locations, each marked with a popup window. Now, I'm looking to implement the functionality that will allow the center of the map to change dynamically when a user clicks o ...

The variants array in VUE.js is not displaying properly

I have recently been delving into vue.js for my work and encountered a significant issue. I wanted to create a simple TODO application. In my index.html file, I only have a div for a header and a root div with an ID: #app. Inside the root div, there is a ...

Access the value of a variable from a window resizing event and utilize it in a different

I have a carousel that I'm working with and am trying to figure out how to announce the number of currently visible slides when the "next" button is clicked. While I can see that on resize, the correct number of slides is being logged, I am strugglin ...

Trouble with Displaying 3rd Level JQuery Dropdown Menu

Currently working on implementing a 3 level dropdown feature. I have been using a third-party responsive menu in Opencart and it's been working well. You can see a demo of it here: Unfortunately, Opencart does not natively support 3 level categories, ...