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

Intersection Observer Proper implementation Preact #4

Open
Jean-Baptiste-Lasselle opened this issue Dec 2, 2023 · 0 comments
Open

Comments

@Jean-Baptiste-Lasselle
Copy link

  • That's to replace the Intersection.vue
  • We need a proper implementation, which spawns an effect while the element enters the viewport

@BorisTherin tiens ds ton prochain commit, tu ajoutes un fichier Intersecting.tsx, avec ce contenu:

import React, { useCallback, useEffect, useState } from "preact/compat";

/**
 * 
 * ---THE IDEA
 * 
 * Ok, so the idea of Intersecting.vue, is 
 * to detect if a component is in the viewport, using
 * new browsers feature named "IntersectionObserver"
 * - 
 * https://vueuse.org/core/useIntersectionObserver/
 * https://stackoverflow.com/questions/45514676/react-check-if-element-is-visible-in-dom
 * 
 */
// useInViewport
export interface IntersectingRender {
  isInViewport: boolean;
  ref: React.RefCallback<HTMLElement>;
}
export const Intersecting = (): IntersectingRender {
  const [isInViewport, setIsInViewport] = useState(false);
  const [refElement, setRefElement] = useState<HTMLElement | null>(null);

  const setRef = useCallback((node: HTMLElement | null) => {
    if (node !== null) {
      setRefElement(node);
    }
  }, []);

  useEffect(() => {
    if (refElement && !isInViewport) {
      const observer = new IntersectionObserver(
        ([entry]) => entry.isIntersecting && setIsInViewport(true)
      );
      observer.observe(refElement);

      return () => {
        observer.disconnect();
      };
    }
  }, [isInViewport, refElement]);

  return { isInViewport, ref: setRef };
}

/**
 * Usage
 * - 
 *  [SomeReactComponent.tsx]
 * - 
 */
/*
import { useInViewport } from "../layout/useInViewport";

export function SomeReactComponent() {
    const { isInViewport, ref } = useInViewport();

    return (
        <>
            <h3>A component which only renders content if it is in the current user viewport</h3>

            <section ref={ref}>{isInViewport && (<ComponentContentOnlyLoadedIfItIsInViewport />)}</section>
        </>
    );
}*/

à voir aussi (très bon, correspond parfaitement à notre cas) :

https://dev.to/sandra_lewis/detecting-the-visibility-of-a-dom-element-in-react-1pp

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

No branches or pull requests

1 participant