score:0

Accepted answer

the window.pageyoffset shows the scrollbar position of the document body. you should be looking for the scrollbar position of the parent element instead.

below there's a hook which you can use to get the scrollbar position of any html element. it attaches an event handler for the scroll event which tracks the element's scrolltop property.

import { usestate, useref, uselayouteffect } from 'react';

export default function usescrollbarposition() {
  const [top, settop] = usestate(0);
  const ref = useref();

  uselayouteffect(() => {
    function gettopposition() {
      const topposition = ref.current.scrolltop;
      settop(topposition);
    }
    ref.current.addeventlistener('scroll', gettopposition);
    gettopposition();
    return () => ref.current.removeeventlistener('scroll', gettopposition);
  }, []);

  return [ref, top];
}

then apply it to your element like this:

import usescrolltop from './use-scroll-top';

function foocomponent() {
  const [ref, top] = usescrolltop();
  console.log(top);

  return (
    <parent ref={ref}>
      <child parentposition={top} />
    </parent>
  );
}

score:0

try to use position: sticky for header https://developer.mozilla.org/en-us/docs/web/css/position


Related Query

More Query from same tag