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

Is there a way to simultaneously click on a link on one page and alter the position of a particular class on another page?

I have been working on designing two pages for a website. I am looking to use JavaScript to ensure that when a link on page 1 is clicked and the user transitions to page 2, the second tab button (btn) will have an id of "default" and receive the activate c ...

I am experiencing an issue where my application, built using NodeJS, Express, and Javascript, is failing to insert form data into the database despite

I am facing a challenge with my app's MVC design pattern where I am unable to insert form information into the corresponding table in the database. Despite installing the body-parser package via npm, the form is not functioning as expected. Can anyone ...

Why is my npm installation generating an ERESOLVE error specifically linked to karma-jasmine-html-reporter?

Could someone help me understand this dependency error I encountered while running npm install and provide guidance on how to resolve such errors? View Error Screenshot I am currently using Angular 16, the latest stable version. npm ERR! code ERESOLVE ...

Utilizing React Router to dynamically render components based on JSON object data

My current challenge involves rendering React components based on the component names in a JSON file I've created. Specifically, I want to render the TestSection component within the context of my Route component. To achieve this, I am utilizing the ...

Navigating through pages in Headless WordPress using WPGraphQL is a breeze

When using Wordpress, I am able to load products on pages with pagination by specifying the page number in the URL like page/2, page/3, etc. Now, in my next.js application, I want to first count all products and then display pagination, loading products f ...

Angular successfully compiled without any issues despite the explicit cast of a number into a string variable

As I delve into the initial concepts of Angular, I have come across a puzzling situation. Here is the code snippet: import { Component } from '@angular/core'; @Component({ selector: 'sandbox', template: ` <h1>Hello {{ nam ...

Struggling to navigate the use of Firebase v3 for hosting my React demo

I need assistance with hosting React apps on Firebase. I recently followed the instructions provided in the new v3 documentation on Firebase.com, but I am unsure about which files/assets should be placed in my public directory. The documentation seemed a b ...

Angular-ui typeahead feature allows users to search through a predefined

I recently developed a typeahead feature using the angular-ui library. Here is the current HTML for my typeahead: <input name="customers" id="customers" type="text" placeholder="enter a customer" ng-model="selectedCustomer" uib-typeahead="customer.fir ...

Data manipulation with Next.js

_APP.JS function MyApp({ Component, pageProps }) { let primary = 'darkMode_Primary'; let secondary = 'darkMode_Secondary' return ( <Layout primary_super={primary} secondary_super={secondary}> <Component {...page ...

What is the speed of communication for Web Worker messages?

One thing I've been pondering is whether transmission to or from a web worker could potentially create a bottleneck. Should we send messages every time an event is triggered, or should we be mindful and try to minimize communication between the two? ...

The resolveMX function in Google Cloud Functions is encountering issues when trying to process a list of domains

Here is the task at hand. I have a large list of domains, over 100,000 in total, and I need to iterate through them using a foreach loop to resolve MX records for each domain. Once resolved, I then save the MX records into another database. Below is the c ...

Necessary Quasar Select Dropdown Class

Looking to set an asterisk (*) next to the Select component in Quasar when it is marked as "required". While I can achieve this with the input component, replicating the same behavior for dropdowns has proved challenging. I attempted using the :deep selec ...

Change the color of the text to be the opposite of the background

I'm facing a challenge while creating a website for my friend. The background of the site is a moving image, and I want the font color of the main title to be the opposite of it on each frame. While I know this may require CSS, I am unsure of how to ...

Using jQuery to create a div that animates when scrolling

Recently, I came across this interesting code snippet: $(document).ready(function(){ $(window).scroll(function(){ if($("#1").offset().top < $(window).scrollTop()); $("#1").animate({"color":"#efbe5c","font-size":"52pt", "top":"0", "position":"fix ...

Attempting to showcase extensive content based on the selection made in a drop-down menu

As a newcomer to anything beyond basic HTML, I am seeking guidance and assistance (preferably explained at a beginner level) for the following issue. If I have overlooked any crucial rules or concepts in my query, I apologize. I aim to have each selection ...

Integrating Vue.js code into Laravel's Blade templates for enhanced functionality

I'm having trouble accessing data from a Vue component function in a Laravel blade template that includes the component. When I use this code, the page just loads as a blank page. However, if I remove the @ symbol from the blade span, the autocomplete ...

ReactJS is making a controlled input of type text into an uncontrolled component with the help of a component transformation

I am encountering a situation where I fetch data from the server and set values in the state for controlled inputs. For example, if I have an input field with a value of this.state.name, I retrieve the name "Dave" from the server and set it in the state as ...

What is the method to assign an initial value to React.createRef()?

Scrolling management in my component is handled through a ref that represents the current scroll value. I've chosen to use refs instead of state and setState because using setState while the user is scrolling would result in a choppy and unresponsive ...

Chrome says it cannot locate the localhost page

Hello everyone, I'm currently working on implementing a reset password route with JWT included in the URL using React Router DOM Route. <Route path={'activate/:activateToken'} element={ ...

Difficulty fetching data on the frontend with Typescript, React, Vite, and Express

I'm currently working on an app utilizing Express in the backend and React in the frontend with typescript. This is also my first time using Vite to build the frontend. While my APIs are functioning correctly, I am facing difficulties fetching data on ...