Experience the innovative feature of React Splide Carousel where a peek of the next image is shown until you reach

My current challenge arises when I reach the last slide in the slider. I am trying to prevent it from looping and instead stop with no extra space or any other images peeking out.

To address this, I have utilized the padding: '5%' option, which mostly works well. However, on the final slide, there is still some additional padding causing a white space.

I attempted to remove the padding once the last slide is reached, but this adjustment ends up making all the images slightly larger and leads to layout shifts.

Another approach I tried was setting perPage: 5.25, but this resulted in strange behavior when navigating between slides.

If anyone has suggestions or ideas to fix this issue, I would greatly appreciate it.

Below is the code snippet I am currently working with:

<Splide
      ref={slideRef}
      className="product-slider"
      hasTrack={false}
      options={{
        type: 'slide',
        perPage: 5,
        pagination: false,
        perMove: 2,
        wheel: true,
        padding: {right: '5%'},
      }}
    >
      <>
        <div className="splide__arrows">
          <button className="splide__arrow splide__arrow--prev">
            <IconChevron direction="right" />
          </button>
          <button className="splide__arrow splide__arrow--next">
            <IconChevron direction="right" />
          </button>
        </div>
        <SplideTrack>
          {slides.map((slide) => {
            return (
              <SplideSlide key={slide.id}>
               <Image />
              </SplideSlide>
            )
          })}
        </SplideTrack>
      </>
    </Splide>

Answer №1

I managed to achieve my desired outcome by referencing Splide and utilizing the on method to determine when it reached the end of the slider.

const slideRef = useRef(null)

  const [padding, setPadding] = useState({right: '5%', left: '0'})

  useEffect(() => {
    slideRef?.current?.splide?.on('moved', () => {
      const currentIndex = slideRef?.current?.splide.index
      const slideLength = slideRef?.current?.splide.length

      if (slideLength - currentIndex === 5) {
        setPadding({right: '0', left: '5%'})
      } else if (currentIndex === 0) {
        setPadding({right: '5%', left: '0'})
      }
    })
  }) 

The number I'm displaying per page is 5.

I also included a class in the Splide Track to improve the transitions when adding or removing padding, creating a smooth bouncing effect.

<SplideTrack className= 'splide-track-padding' /> 

.splide-track-padding {
  transition: padding-left .3s ease-in-out, padding-right .3s ease-in-out;
}

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

Making a page jump with Javascript

Welcome! Let's dive into our question. Below you'll find my script and HTML code: My Script: const resultEl = document.querySelector('.allquotes'); const pageSize = document.querySelector('select[name="page-size"]') ...

Using JQuery to fill an HTML dropdown menu with data from a JSON file

I've been struggling with this issue for a while and despite reading through other posts, I still can't seem to get it to work. My problem lies in populating a drop down menu with JSON data. Although the drop down menu appears on my HTML page, i ...

What is the process for displaying a document file in an iframe that is returned from a link's action?

I have a main page called index.cshtml. This page displays a list of document files along with an iframe next to it. My goal is to load the selected document file into the iframe when I click on any item in the list. However, currently, when I click on a d ...

Newly included JavaScript file displays on view page, but triggers a 404 error when attempting to open

Once I implemented the following code in the child theme's function.php file: add_action('wp_enqueue_scripts', 'js_files'); function js_files() { wp_register_script('ajax_call_mkto', get_template_directory_uri() . ' ...

Issue with the dynamic updating of props

Every time a radio button is clicked within Test.js, the handleclick function executes, updating an array. However, the issue lies in not sending this updated array back to graph_test.js. As a result, graph_test.js only receives the initial array filled wi ...

Ways to secure a floating item onto a backdrop picture

Currently I am working on editing this page. When you hover over the cat, its eyes blink or two black dots randomly appear. My goal is to prevent the random blinking dots from appearing. I want to keep the hover object attached to the cat/background image ...

There seems to be an issue as the function reporter.beforeLaunch cannot be identified and

I am currently attempting to incorporate the protractor screenshot reporter for jasmine 2. However, I encountered the following error in the terminal: /usr/local/bin/node lib/cli.js example/conf.js /Users/sadiq/node_modules/protractor/node_modules/q/q.j ...

What is the most efficient method of organizing form components together?

After exploring numerous tutorials, I have yet to discover the ideal solution for properly marking up a form that contains logical groupings of elements such as labels, controls (input or select), and previous values - essentially single fields. My prefer ...

Sending a JavaScript object as a prop in a React component

Currently, I am enrolled in a React course that requires us to pass a single JavaScript object as props to a React application. Here's the code snippet I have been working on: import React from 'react'; import ReactDOM from 'react-dom& ...

Develop a game timer using CreateJS

Looking for advice on the most effective method to create a timer clock using Createjs. I've attempted to reference HTML elements with DOMElement in the past, but encountered difficulties. Essentially, I need to display a timer within a container so p ...

Adjusting the size of several images individually with jquery

Currently, I am working on a jQuery script that enables me to resize any image by simply clicking on it. The goal is to have the ability to click on one image and resize it, then click on another image and resize it independently. Here is the code I have b ...

Angular $resource encounters a 400 Bad Request error when attempting a PUT request, triggering the $resolve and $promise

My service is structured as follows (with variables removed): angular .module('app') .factory('Employee', function($resource) { return $resource("https://api.mongolab.com/api/1/databases/:dbName/collections/:collectionN ...

How can I load a specific div region using ajax for submitting a form?

I'm not sure if my approach is correct. On my main page, I have some information displayed. When you click a button, the form will load from a separate file: $('#viewport').load('/views/myView.php #targetDiv') This works fine ...

Steps to modify the text of the accept and cancel buttons on the MobileDatePicker component

The MobileDatePicker component in the @mui/x-date-pickers package features buttons labeled as OK/CANCEL by default. In version 4 of the DatePicker component, there was a prop called acceptLabel/cancelLabel that allowed changing the text of the buttons. Ho ...

Struggling to adjust the quantity of items in a basic shopping cart when adding multiples of the same item

Hello there! I'm currently working on a project where I need to increase the quantity of each item added to the cart if it's already in there. This is actually my first time posting, so any tips on asking better questions would be greatly appreci ...

Encountering a 'Object is not a function' issue while attempting to implement Page Object with Protractor

Whenever I attempt to run my tests, I keep encountering a TypeError: object is not a function. Prior to incorporating PageObject, everything worked fine. Below is my spec.js 'use strict'; var todoAppPage = require('../pages/angular.page&a ...

Is it possible to save the current permissions for a channel or category in Discord.js and then restore them after a certain event occurs?

A Little Background I recently came across a lockdown command on YT that locks down all channels in the guild when you type "!lockdown". This command overwrites channel permissions for specific roles. However, when we unlock the channels, everyone is able ...

"Upon setting the state in React, the Full Calendar refreshes and retrieves events

My current setup involves using the FullCalendar API to fetch events as shown below: <FullCalendar ref={calendarRef} plugins={[listPlugin, bootstrap5Plugin]} initialView='listMonth' ...

Understanding how to sum the values of two separate dropdown selections using jQuery

Is it possible to combine and total up two different selections to display on the "Total" button below? I have added calculations to each selection. When a user selects a quantity, it should automatically sum up and display on the "Total" button, but I am ...

Removing Borders from Dropdown Tabs in Bootstrap Navbar: A Step-by-Step Guide

I am facing an issue while using Bootstrap 4, as I am unable to remove the border that appears when selecting the drop-down tab. Here is a glimpse of the problem You can view the Inspector View here Check out the relevant code snippet ...