react-use-scrollspy icon indicating copy to clipboard operation
react-use-scrollspy copied to clipboard

Question: How to handle sections with small height at the bottom of the page?

Open saini-g opened this issue 3 years ago • 4 comments

First of all, thanks for the fantastic hook. Works like a charm! 👍

So, I have a page with dynamically generated sections with editable content, so the last section on the page sometimes has a small height say 100px and doesn't trigger the hook like it should be for other sections on the page The hook works perfectly, even for the last section on the page, if it's height is large enough to be covered into the threshold value calculated using the offsetPx prop

import useScrollSpy from 'react-use-scrollspy';

// if I have 3 sections, and the height of the 3rd(last) section is small
// then activeSection value is never set to its index value i.e. 2
const activeSection = useScrollSpy({
  sectionElementRefs: sectionRefsArray,
  offsetPx: Y_OFFSET
});

Is there any way to handle this scenario?

saini-g avatar May 24 '21 09:05 saini-g

Hey @saini-g! Glad the component helps you 👍

Do you have an example with code sandbox or something?

Purii avatar May 24 '21 12:05 Purii

@Purii https://codesandbox.io/s/hardcore-beaver-wdp7q

saini-g avatar May 26 '21 12:05 saini-g

@saini-g thanks for the sandbox!

I should extend the api to allow setting a threshold, so you can configure it per element. However I won't be able to do that in the next days. In the meantime you could give the Intersection Oberserver API a chance (e.g. react-use provides a hook for that: https://github.com/streamich/react-use/blob/master/docs/useIntersection.md)

Purii avatar May 26 '21 15:05 Purii

No worries @Purii , I'm not in urgent need of a solution. I previously tried giving the Intersection Observer a shot, but it doesn't tell you the scroll position of an element, so in my opinion it becomes somewhat less than ideal for the scrollspy use case.

For the problem I am facing with the short elements at the bottom of the page, I thought of a solution like if the page is scrolled all the way to the bottom, then we could set the active section to the last section irrespective of the offset. If it meets the offset then it would already be the active section and this logic would not have any negative effects, and if it doesn't meet the offset then the desired/expected behaviour could be achieved by this logic.

My thoughts on your solution

I should extend the api to allow setting a threshold, so you can configure it per element

Although rarely, but there could be conflicting active sections, i.e. more than 1 sections could possibly meet the offset value simultaneously, but now that I think about it, this is bound to happen any time there are more than 1 logics to determine the active section, even in my suggestion above.

saini-g avatar May 26 '21 17:05 saini-g