Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bug: Changing element breaks use-in-viewport hook #6812

Closed
2 tasks done
fellmann opened this issue Sep 12, 2024 · 1 comment · Fixed by #6926
Closed
2 tasks done

Bug: Changing element breaks use-in-viewport hook #6812

fellmann opened this issue Sep 12, 2024 · 1 comment · Fixed by #6926

Comments

@fellmann
Copy link
Contributor

fellmann commented Sep 12, 2024

Dependencies check up

  • I have verified that I use latest version of all @mantine/* packages

What version of @mantine/* packages do you have in package.json?

7.12.2

What package has an issue?

@mantine/hooks

What framework do you use?

Vite

In which browsers you can reproduce the issue?

All

Describe the bug

The use-in-viewport hook does not react to changes of the ref. If the observed element changes, it stops working.

If possible, include a link to a codesandbox with a minimal reproduction

https://codesandbox.io/p/sandbox/mantine-react-template-forked-nlnrm7

Possible fix

After some problems especially in StrictMode / Dev, I found a simple but working solution:

import { useCallback, useRef, useState } from "react";

export function useInViewport<T extends HTMLElement>() {
  const observer = useRef<IntersectionObserver | null>(null);
  const [inViewport, setInViewport] = useState(false);

  const ref = useCallback((node: T | null) => {
    if (typeof IntersectionObserver !== "undefined") {
      if (node && !observer.current) {
        observer.current = new IntersectionObserver(([entry]) =>
          setInViewport(entry.isIntersecting)
        );
      } else {
        observer.current?.disconnect();
      }
      
      if (node) {
        observer.current?.observe(node);
      } else {
        setInViewport(false);
      }
    }
  }, []);

  return { ref, inViewport };
}

Self-service

  • I would be willing to implement a fix for this issue
@ashar-nadeem-lumi
Copy link

@fellmann Thanks for the fixed code, made a custom hook and this works great now. Would be nice to have this fix merged in, definitely wasted a lot of time on this bug

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 a pull request may close this issue.

2 participants