Skip to content

[@mantine/hooks] use-scroll-spy: Accept a ref object for scrollHost option#9031

Open
Hossam-Ismail wants to merge 1 commit into
mantinedev:masterfrom
Hossam-Ismail:feat/use-scroll-spy-ref-host
Open

[@mantine/hooks] use-scroll-spy: Accept a ref object for scrollHost option#9031
Hossam-Ismail wants to merge 1 commit into
mantinedev:masterfrom
Hossam-Ismail:feat/use-scroll-spy-ref-host

Conversation

@Hossam-Ismail

Copy link
Copy Markdown

Closes #9025

Currently useScrollSpy's scrollHost option only accepts a resolved HTMLElement. The idiomatic way to obtain a DOM node in React is a ref, but a ref's .current is undefined on first render, so users have to convert the element into state via a callback ref just to make the hook re-initialize once the host exists:

const [scrollHost, setScrollHost] = useState<HTMLElement | null>(null);
useScrollSpy({ scrollHost: scrollHost ?? undefined, selector });
return <form ref={setScrollHost}></form>;

This change lets scrollHost accept either a resolved element or a ref object, collapsing the usage to the natural form:

const scrollHostRef = useRef<HTMLDivElement>(null);
useScrollSpy({ scrollHost: scrollHostRef, selector });
return <div ref={scrollHostRef}></div>;

Because the listener is attached inside useEffect (which runs after the DOM is committed), ref.current is already populated by the time the host is resolved, so no extra state/re-render is required. This mirrors the existing pattern of other hooks such as use-scroll-into-view, which already accept a RefObject.

Changes

  • Widen scrollHost type to HTMLElement | RefObject<HTMLElement | null>.
  • Resolve .current inside the effect when a ref object is passed; fall back to window when the resolved host is null/undefined (unchanged behavior for the existing HTMLElement and no-arg cases).
  • Update the JSDoc for the option.

Tests

Added use-scroll-spy.test.ts covering: default window host, a resolved HTMLElement host, a ref-object host, and a ref whose current is null (falls back to window).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

useScrollSpy: accept a RefObject<HTMLElement> for scrollHost, not just a resolved HTMLElement

1 participant