2.0.2 • Published 2 years ago

react-viewport-detect v2.0.2

Weekly downloads
-
License
GPL-3.0-or-later
Repository
github
Last release
2 years ago

React viewport detect

A React hook to detect if an HTML Element has been display in the viewport. This is easy to use. You just have to provide an react ref. By default it freeze the value when the element has been display. That is nice to triggered one time animation !

NPM Version Minified size GPLv3 License

Demo

example page

Usage

Basic Usage

import {useViewportDetection} from "react-viewport-detect";
import {useRef, useEffect} from "react" ;

const App () => {
    
    const ref = useRef() ; 
    const isVisible = useViewportDetection(ref) ;

    useEffect(() => {
        console.log(isVisible) ;
    },[isVisible]) ;
    
    return (
        <div>
            <h1>React visible hook</h1>
            <div ref={ref} >
                <p>
                    Do I am visible ? 
                </p>
            </div>
        </div>
    );
    
};

Advanced

import {useViewportDetection} from "react-viewport-detect";
import {useRef, useEffect} from "react" ;

const App () => {
    
    const ref = useRef() ; 
    const isVisible = useViewportDetection(ref, {freeze: false, threshold: 1}) ;

    useEffect(() => {
        console.log(isVisible) ;
    },[isVisible]) ;
    
    return (
        <div>
            <h1>React visible hook</h1>
            <div ref={ref} >
                <p>
                    Do I am visible ? 
                </p>
            </div>
        </div>
    );
    
};

Function parameters

useViewportDetection

ParameterTypeDescriptionDefault
refReact refThe React ref to detectnone
{rootMargin, root, threshold, freeze}ArrayIntersection Observer options + freeze. Freeze is to keep the value when it has been display once{rootMargin = 0px, root = null, threshold = 0, freeze = true}

More about Intersection Observer options

Next steps

  • TypeScript Support
  • Improve the DX
  • Unit Testing

Contributing

Contributions are always welcome! You can create a new pull request with changes or create a new issue and I will update this project