roderickhsiao / react-in-viewport

Detect if React component is in viewport
https://roderickhsiao.github.io/react-in-viewport
MIT License
350 stars 30 forks source link

useInViewport for multiple elements #113

Closed michalk91 closed 2 years ago

michalk91 commented 2 years ago

I have problem, i creating moving thumbnails for my carousel slider. When thumbnails container is it does not fit in Viewport and active thumb is outside i want move my active thumb to viewport. Now useInViewport returns "true" when whole thumbs container is in Viewport and "false" when some part of him is out. I want have value "true" or "false" for each individual thumb. It is possible when i using hook?

i added a ref to each thumb as below:

    _{lightboxThumbsVisible === true &&
            React.Children.map(children, (child, index) => {
              return (
                <div
                  ref={thumbRef}
                  key={index}
                  data-id={index}
                  className={classNames(styles.dot, {
                    [styles.active]: index === activedIndex,
                  })}
                  onClick={onNavigate}
                >
                  {images[index]}
                </div>
              );
            })}_

Thank you for Your anwser, Greetings.

roderickhsiao commented 2 years ago

Not sure if I understand correctly, you want to track individual thumb on a horizontal scroll?

The library use intersection observer under the hood.

If that's the case you can check https://codesandbox.io/s/frosty-hooks-fptryw?file=/src/styles.css

you can bind useInViewport on the individual child instead of parent container.

michalk91 commented 2 years ago

That's what I meant. Problem solved. Thank you very much!