hades255 / angela-pm-fe

Chat app for the admin
1 stars 0 forks source link

Trigger view on the component #3

Closed hades255 closed 6 hours ago

hades255 commented 6 hours ago

set read when you see chat message

hades255 commented 6 hours ago

make a hook named useOnScreen

import { useEffect, useState } from "react";

const useOnScreen = (ref) => {
  const [isIntersecting, setIntersecting] = useState(false);

  useEffect(() => {
    const currentRef = ref.current;
    const observer = new IntersectionObserver(
      ([entry]) => setIntersecting(entry.isIntersecting),
      {
        root: null, // Use the browser viewport as the container
        rootMargin: "0px",
        threshold: 0.1, // Trigger when at least 10% of the target is visible
      }
    );

    if (currentRef) {
      observer.observe(currentRef);
    }

    return () => {
      if (currentRef) {
        observer.unobserve(currentRef);
      }
    };
  }, [ref]);

  return isIntersecting;
};

export default useOnScreen;
hades255 commented 6 hours ago

use useOnScreen hook on the component

import useOnScreen from '@hooks/useOnScreen'
...
const isVisible = useOnScreen(ref)