Giter Site home page Giter Site logo

react-hook-inview's Introduction

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
  defaultInView?: boolean, // false
}

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

react-hook-inview's People

Contributors

bitmap avatar dependabot[bot] avatar hoangnguyen1247 avatar krazyjakee avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

react-hook-inview's Issues

Add tests

Add tests for react-hook-inview

  • Jest
  • @testing-library/jest-dom
  • @testing-library/react

"Syntax Error" in IE11

The hook does not work in IE11. It throws "Syntax Error" at "./node_modules/react-hook-inview/dist/esm/index.js"

Can't access updated state in onEnter

Hi,

I'm trying to access state that has changed when my component comes into view but it seems that the state is locked to when the hook is initialized.

const [someValue, setSomeValue] = useState(1111);

// Only call once.
 useEffect(() => {
   setSomeValue(2222)
 }, []);

 useInView({
   target: element,
   threshold: 0.25,
   onEnter: () => { console.log(someValue) },
   unobserveOnEnter: true
 }, [someValue]);

When the item comes into view, onEnter is called but the output is "1111" rather than "2222" even though the state has been updated. What is the right way to be able to access the state in the onEnter callback?

This is a great product, thank you

This is an awesome product!

I just set it up for a quick app and it worked like a charm. ๐Ÿ‘Œ

Feel free to close this issue after reading! ๐ŸŽ‰

when threshold is array, componment while loop render

bad

function App() {
  const root = useRef();

  const [ref, isVisible] = useInView({
    root: root.current,
    threshold: [0]
  })

  console.log(isVisible, '?')
// ...

good

const threshold = [0]
function App() {
  const root = useRef();

  const [ref, isVisible] = useInView({
    root: root.current,
    threshold,
  })

  console.log(isVisible, '?')
 // ....

Problems with firefox

I tested in firefox dunno why the inview stay in true with the component out of the viewport also tried with onEnter and onLeave, the onLeave is not being executed in firefox.

const [componentId, setComponentId] = useState(null);
const [ref, inView] = useInView({
threshold: 0.7,
});

useLayoutEffect(() => {
effectCallback && effectCallback(inView);
inView && setLoaded(true);
}, [inView, effectCallback]);

return (
<div
id={stickyNavId}
className={${className}${ inView && componentId === stickyNavId ? " ns-inview" : "" }}
data-id={componentID}
style={style}
ref={ref}
>
{(loaded || inView) && children}
</div>
);
};

unobserveOnEnter doesn't seem to be working

Hey, trying to use the unobserveOnEnter, but it does not seem to be working.

Here's what I am using:

const [ref, inView] = useInView({ unobserveOnEnter: true })
console.log(inView)

but this flips between true and false as I scroll past the item.

React 18 support

Hi, thanks for the great library.
the library only supports: react@"^16.8.0 || ^17.0.0"

pls also support 18
thanks.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.