All Projects → bitmap → React Hook Inview

bitmap / React Hook Inview

Licence: mit
React hook for detecting when an element is in the viewport

Programming Languages

typescript
32286 projects

Labels

Projects that are alternatives of or similar to React Hook Inview

vw-layout
Mobile website layout with viewport units
Stars: ✭ 47 (-9.62%)
Mutual labels:  viewport
Vue Mq
📱 💻 Define your breakpoints and build responsive design semantically and declaratively in a mobile-first way with Vue.
Stars: ✭ 474 (+811.54%)
Mutual labels:  viewport
Verge
Get viewport dimensions, detect elements in the viewport
Stars: ✭ 687 (+1221.15%)
Mutual labels:  viewport
Stickystack.js
A jQuery plugin that creates a stacking effect by sticking panels as they reach the top of the viewport.
Stars: ✭ 287 (+451.92%)
Mutual labels:  viewport
React On Screen
Check if a react component in the viewport
Stars: ✭ 357 (+586.54%)
Mutual labels:  viewport
In View
Get notified when a DOM element enters or exits the viewport. 👀
Stars: ✭ 4,684 (+8907.69%)
Mutual labels:  viewport
react-awesome-reveal
React components to add reveal animations using the Intersection Observer API and CSS Animations.
Stars: ✭ 564 (+984.62%)
Mutual labels:  viewport
Viewprt
A tiny, dependency-free, high performance viewport position & intersection observation tool
Stars: ✭ 36 (-30.77%)
Mutual labels:  viewport
React Socks
🎉 React library to render components only on specific viewports 🔥
Stars: ✭ 400 (+669.23%)
Mutual labels:  viewport
Isinviewport
An ultra-light jQuery plugin that tells you if an element is in the viewport but with a twist.
Stars: ✭ 646 (+1142.31%)
Mutual labels:  viewport
Scrollmonitor
A simple and fast API to monitor elements as you scroll
Stars: ✭ 3,250 (+6150%)
Mutual labels:  viewport
React Awesome Reveal
React components to add reveal animations using the Intersection Observer API and CSS Animations.
Stars: ✭ 346 (+565.38%)
Mutual labels:  viewport
Pixi Viewport
A highly configurable viewport/2D camera designed to work with pixi.js
Stars: ✭ 532 (+923.08%)
Mutual labels:  viewport
viewport-spy
Godot editor UI to spy on what a Viewport is rendering. Useful for debugging.
Stars: ✭ 28 (-46.15%)
Mutual labels:  viewport
React Cool Inview
😎 🖥️ React hook to monitor an element enters or leaves the viewport (or another element).
Stars: ✭ 830 (+1496.15%)
Mutual labels:  viewport
svelte-intersection-observer
Detect if an element is in the viewport using the Intersection Observer API
Stars: ✭ 151 (+190.38%)
Mutual labels:  viewport
Motus
Animation library that mimics CSS keyframes when scrolling.
Stars: ✭ 502 (+865.38%)
Mutual labels:  viewport
Pixi Cull
a library to visibly cull objects designed to work with pixi.js
Stars: ✭ 51 (-1.92%)
Mutual labels:  viewport
React Intersection Observer
React component for the Intersection <Observer /> API
Stars: ✭ 940 (+1707.69%)
Mutual labels:  viewport
Viewport Checker
Little utility to detect if elements are currently within the viewport 🔧
Stars: ✭ 596 (+1046.15%)
Mutual labels:  viewport

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).

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 a tuple with four items:

  • A ref callback, used to set observer on an element.
  • A boolean when the element is in the viewport.
  • The IntersectionObserverEntry
  • 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 your own ref object
}

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.

onEnter & onLeave callbacks

⚠️ These options are deprecated, and support may be removed in a future release. To access the intersection observer callback, use the useInViewEffect hook instead.

onEnter and onLeave recieve a callback function that returns an IntersectionObserverEntry and the IntersectionObserver itself. The two arguments are entirely optional.

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

NOTE: If you supply an array with multiple values to threshold, onEnter will be called each time 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 external state in callbacks

For performance reasons, the hook is only triggered once on mount. 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 update callback

This will remount the intersection observer, and may have unintended side effects. Use this feature with caution.

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 as it doesn't obfuscate the Intersection Observer API as much.

const ref = useInViewEffect(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) => {
      if (entry.isIntersecting) {
        observer.unobserve(entry.target)
      }
      setIsVisible(entry.isIntersecting)
    },
    { threshold: 0.5 },
  )

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

Keep in mind that the first argument will return an array.

Options

The useInViewEffect hook has more limited options that mirror 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

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].