@alemesa/react-use-intersection-observer

1.0.3 • Public • Published

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!

Package Sidebar

Install

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

Weekly Downloads

1

Version

1.0.3

License

MIT

Unpacked Size

6.68 kB

Total Files

4

Last publish

Collaborators

  • alemesa