@alemesa/react-use-intersection-observer

React Hook that uses the intersection observer API

Usage no npm install needed!

<script type="module">
  import alemesaReactUseIntersectionObserver from 'https://cdn.skypack.dev/@alemesa/react-use-intersection-observer';
</script>

README

react-use-intersection-observer

All Contributors

Version MIT license Size

NPM

React Hook that uses the intersection observer API

Usage

npm i @alemesa/react-use-intersection-observer

  • Example Codesanbox:

Edit react-use-intersection-observer


  • Simple Example: Element will trigger a single time and unobserve
import React, { useRef, useEffect } from "react";
import useIntersectionObserver from "@alemesa/react-use-intersection-observer";

const Header = React.memo(() => {
  const elRef = useRef(null);

  // Pass a reference to the custom hook
  const intersected = useIntersectionObserver(elRef);

  useEffect(() => {
    if (intersected) {
      // Intersected - do whatever you want
      console.log("Intersected element");
    }
  }, [intersected]);

  return <h3 ref={elRef}>Example</h3>;
});

export default Header;

  • Custom Example: Element will trigger multiple time
import React, { useRef, useEffect } from "react";
import useIntersectionObserver from "@alemesa/react-use-intersection-observer";

const Header = React.memo(() => {
  const elRef = useRef(null);

  // Pass a reference to the custom hook and custom options
  const intersected = useIntersectionObserver(elRef, {
    triggerOnce: false,
    threshold: 0.3,
    rootMargin: "-150px"
  });

  useEffect(() => {
    if (intersected) {
      // Intersected - do whatever you want
      console.log("Intersected element");
    }
  }, [intersected]);

  return <h3 ref={elRef}>Example</h3>;
});

export default Header;

Contributors

Thanks goes to these wonderful people (emoji key):

Alejandro Mesa
Alejandro Mesa

🚇 💻
Donghyuk (Jacob) Jang
Donghyuk (Jacob) Jang

💻

This project follows the all-contributors specification. Contributions of any kind welcome!