useInViewRef

About

Simple hook that monitors element enters or leave the viewport that's using Intersection Observer API.


It returns a ref to observed element, as well as boolean flag - inView that will tell if the element is inside of the viewport / parent element or not. You can also pass a callback that will be fired everytime the Observer will be triggered. To understand the Intersection Observer API better, please check its documentation on MDN.

Examples

Basic example

import "./styles.css";
import { useInViewRef } from "rooks";

export default function App() {
  const [myRef, inView] = useInViewRef();
  return (
    <>
      <div
        style={{
          position: "fixed",
          top: 0,
          left: 0,
        }}
      >
        <h1>Is rectangle visible - {String(inView)}</h1>
      </div>
      <div style={{ height: 2000 }}></div>
      <div ref={myRef} style={{ height: 300, background: "red" }}></div>
      <div style={{ height: 2000 }}></div>
    </>
  );
}

Arguments

ArgumentTypeDescriptionDefault ValueRequired
callbackIntersectionObserverCallbackCallback that will be fired when the intersection occursundefinedno
optionsIntersectionObserverInitIntersection Observer config (read more){ root: null,rootMargin: "0px 0px 0px 0px", threshold: [0, 1]}no

Return

Returns an array with the first element in the array being the callback ref for the React component/element that needs to be observed and a second being the boolean flag that indicates if the element is in viewport.

Return valueTypeDescriptionDefault value
refCallbackRefref for the React component/element that needs to be observed.null
inViewbooleanflag that will indicate if the element is in viewportfalse

Join the community!

Join our discord server! You can click the floating discord icon at the bottom right of the screen and chat with us!

Powered by vercel