Search code examples
javascriptreactjsreact-hooksscrollbarcss-position

How to move a scrollbar together with the left position of its <div> (possibly with React)


I have an horizontal slider with lots of "cards".

horizontal slider

The JS code that defines its CSS is as follows:

    cardCarouselSlider: {
      zIndex: 0,
      overflow: 'hidden',
      width: 300 * cardsNumber,
      height: 200,
      position: 'absolute',
      left: (targetedPlanIndex >= 0)
        ? -281 * targetedPlanIndex + 40
        : -281 * (targetedPlanIndex + 1) + 40,
      transition: 'left 0.5s ease',
    },

As the value of left shows, I can have the slider slide horizontally by changing the value of targetedPlanIndex.

However, my customer wants to have also a scrollbar (you see it in the image) to be able to scroll rapidly between the cards.

Problem is: when I increase targetedPlanIndex, the slider scrolls to the left, but the scrollbar remains always glued to its start position. See next image, where the index was increased by 1:

horizontal slider - index increased

I'd like to see the scrollbar slide to the right as the slider goes left, as it would happen if I used the scrollbar to move the slider (see third image).

scrolling with the scrollbar

Any idea how I could do this?

My page is built with React, so basically I believe I am willing to attach some scroll event listener to my slider div, and not to the whole document. After that, there should be some useScrollPosition hook to tinker with.


Solution

  • After pursuing this quest for another couple of days, I haven't been able to find examples of React hooks that are able to detect/manage the scroll of individual components in page, let alone horizontal scroll.

    I have solved my problem by leaving CSS aside and putting in place a JS/DOM-based solution, catering to the Element methods that control scroll.

    These React solutions are all based on using a useRef hook tied to the page Element that is to be controlled, and accessing its methods through the current property of the reference.

    The main drawback of these solutions is that (regardless of what the standards seem to promise) I cannot exploit CSS easing functions to implement a smooth scroll transition: for that I was forced to use a setInterval/setTimeout solution to perform many partial scrolls of my component.