JSPM

  • Created
  • Published
  • Downloads 16507
  • Score
    100M100P100Q134624F
  • License MIT

React Hook for detecting when an element is in the viewport

Package Exports

  • react-hook-inview

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (react-hook-inview) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

react-hook-inview

npm version

Detect if an element is in the viewport using a React Hook. Utilizes the Intersection Observer API, so check for compatibility.

Install

npm install react-hook-inview

Optional: Install a polyfill for browsers that don't support IntersectionObserver yet (i.e. Safari 12).

Usage

Hooks can only be used inside functional components.

useInView

The hook in its most basic form returns a ref and a boolean.

const [ref, inView] = useInView()

That's all you need to get started, but it does a lot more.

Example

In this example, the boolean is used to toggle some text on and off when the element is fully in the viewport.

import React from 'react'
import { useInView } from 'react-hook-inview'

const Component = () => {

  const [ref, isVisible] = useInView({
    threshold: 1,
  })

  return (
    <div ref={ref}>
      {isVisible
        ? 'Hello World!'
        : ''
      }
    </div>
  )
}

API

The hook returns four variables.

  • A ref, used to reference a React node.
  • A boolean when the element is in the viewport.
  • The IntersectionObserver entry
  • The IntersectionObserver itself
const [ref, inView, entry, observer] = useInView(options, [...state])

Options

These are the default options.

{
  root?: RefObject<Element> | null, // Optional, must be a parent of your ref
  rootMargin?: string,              // '0px' or '0px 0px 0px 0px', also accepts '%' unit
  threshold?: number | number[],    // 0.5 or [0, 0.5, 1]
  unobserveOnEnter?: boolean,       // Set 'true' to run only once
  onEnter?: (entry?, observer?) => void, // See below
  onLeave?: (entry?, observer?) => void, // See below
  target?: RefObject<Element> | null,    // *DEPRECATED* Supply a ref object create by React
}

Note If you're updating from < version 4.0.0., you might have noticed an API changed. The target option has been deprecated, but still works the same way.

Callbacks

onEnter and onLeave recieve a function that returns an IntersectionObserverEntry and the observer itself.

function onEnter(entry, observer) {
  // entry.boundingClientRect
  // entry.intersectionRatio
  // entry.intersectionRect
  // entry.isIntersecting
  // entry.rootBounds
  // entry.target
  // entry.time
}

NOTE: If you supply an array to threshold, onEnter will be called when the element intersects with the top and bottom of the viewport. onLeave will on trigger once the element has left the viewport at the first threshold specified.

Accessing state in callback

For performance reasons, the hook is only triggered once on mount/unmount. However, this means you can't access updated state in the onEnter/onLeave callbacks. An optional second argument will retrigger the hook to mitigate this.

// Some other state
const [state, setState] = useState(false)

const[ref, inView] = useInView({
  onEnter: () => console.log(state),
}, [state]) // <- Will rerender ref and update callback

useInViewEffect

An alternate hook that allows you to just supply the intersection observer callback. This approach is gives you a little more flexibilty than using the callbacks in the original hook, and doesn't obfuscate the Intersection Observer API as much.

const ref = useInView(callback, options, [...state])

Example

import React, { useState } from 'react'
import { useInViewEffect } from 'react-hook-inview'

const Component = () => {
  const [isVisible, setIsVisible] = useState(false)

  const ref = useInViewEffect(([entry], observer) => {
      setIsVisible(entry.isIntersecting)
      observer.unobserve(entry.target)
  }, {threshold: 0.5})

  return (
    <div ref={ref}>
      {isVisible
        ? 'Hello World!'
        : ''
      }
    </div>
  )
}

Keep in mind that the entries will be an array.

Options

The useInViewEffect hook has more limited options that match the default API.

{
  root?: RefObject<Element> | null, // Optional, must be a parent of your ref
  rootMargin?: string,              // '0px' or '0px 0px 0px 0px', also accepts '%' unit
  threshold?: number | number[],    // 0.5 or [0, 0.5, 1]
}

License

MIT