useInView
Determine if an element is currently in the viewport or not using IntersectionObserver.
Note: This uses the IntersectionObserver API which is not available in all browsers yet, so you might want to polyfill it before using this hook.
Usage
import React, { useRef } from 'react';import { useInView } from '@fransvilhelm/hooks';const Reveal = ({ children }) => {const ref = useRef();const inView = useInView(ref);return (<divref={ref}style={{opacity: inView ? 1 : 0,transition: 'opacity 1s ease-in-out',}}>{children}</div>);};
Example
The text below will change between visible and hidden when it passes the edges of the window (currently with a 15% margin inwards for demonstration purposes).
There's some extensive padding added to the bottom of this page to demonstrate what happens when the object gets close to the edge.
Currently: hidden
Parameters
useInView
accepts two arguments – the element (as a ref container) to observe
and optional options to attach to the IntersectionObserver.
Param | Type | Required | Default | Description |
---|---|---|---|---|
ref | RefObject\<Element> | true | - | A ref object with a current value of an HTML Element |
options | IntersectionObserverInit | false | - | IntersectionObserver options |
Returns
useInView
returns a boolean indication if the current element is in view or
not.