Newer
Older
My-Portfolio / frontend / src / components / sections / SectionObserver.jsx
import { useEffect, useState } from "react";

const SectionObserver = () => {
  const [activeSections, setActiveSections] = useState(new Set());

  useEffect(() => {
    const updateSections = () => {
      const sections = document.querySelectorAll("section");

      if (sections.length === 0) return; // Prevent observer from running if no sections

      const handleIntersection = (entries) => {
        entries.forEach((entry) => {
          setActiveSections((prevActiveSections) => {
            const newActiveSections = new Set(prevActiveSections);
            if (entry.isIntersecting) {
              newActiveSections.add(entry.target.id);
            } else {
              newActiveSections.delete(entry.target.id);
            }
            return newActiveSections;
          });
        });
      };

      const observer = new IntersectionObserver(handleIntersection, {
        threshold: 0.1,
        rootMargin: "40px 0px -40px 0px",
      });

      sections.forEach((section) => observer.observe(section));

      return () => {
        sections.forEach((section) => observer.unobserve(section));
      };
    };

    // Run updateSections initially in case sections already exist
    updateSections();

    // Observe DOM changes to detect when sections are added dynamically
    const mutationObserver = new MutationObserver(updateSections);
    mutationObserver.observe(document.body, { childList: true, subtree: true });

    return () => mutationObserver.disconnect();
  }, []);

  return activeSections;
};

export default SectionObserver;