1.1.1 • Published 5 years ago
react-visibility-detector v1.1.1
React visibility detector
A React component that notifies you when it enters or exits the viewport. Based on a IntersectionObserver, resulting in improved performance. Not supported by IE and some others, see here - https://caniuse.com/?search=IntersectionObserver
Install
yarn add react-visibility-detector
Example
To run the example locally:
yarn buildcd exampleyarnyarn start- open
http://localhost:1234in your browser
General usage goes something like:
import VisibilityDetector from 'react-visibility-detector';
function handleVisibilityChange ({ visible, directionX, directionY }) {
console.log('Element is now %s', visible ? 'visible' : 'hidden');
console.log('Horizontal direction %s', directionX); // left, right, or none if no changed or initial
console.log('Vertical direction %s', directionY); // up, down or none if no changed or initial
}
function MyComponent (props) {
return (
<VisibilityDetector onVisibilityChange={handleVisibilityChange}>
<div>...content goes here...</div>
</VisibilityDetector>
);
}
// with hook
import { useChangeVisibility } from 'react-visibility-detector';
function onVisibilityChange ({ visible, directionX, directionY }) {
console.log('Element is now %s', visible ? 'visible' : 'hidden');
console.log('Horizontal direction %s', directionX); // left, right, or none if no changed or initial
console.log('Vertical direction %s', directionY); // up, down or none if no changed or initial
}
function MyComponent (props) {
const targetRef = useRef(null);
useChangeVisibility({ targetRef, onVisibilityChange });
return (
<div ref={targetRef}>...content goes here...</div>
);
}Try it out
Run the example.
Props
classNamecss class for styling, defaultundefineddistance- distance to the viewport at which the detector will trigger, default0onVisibilityChange- callback, called when changed detector visibilitychildren
Hook props
distance- distance to the viewport at which the detector will trigger, default0onVisibilityChange- callback, called when changed detector visibilitytargetRef- ref to target element
License
MIT