1.0.11 • Published 3 years ago
react-hook-simple-inview v1.0.11
react-hook-simple-inview
Simple React Hook is for monitoring when an element is in the viewport.
Install
$ npm i react-hook-simple-inview --save
Usage
Simple React Hook makes monitoring easier when an element is in the viewport. You can use it for example for virtual scroll - remove an element from DOM when it is outside of the main wrapper.
import useInView from 'react-hook-simple-inview';
const MainComponent = () => {
const rootRef = React.useRef(null);
const padding = 200;
const [inViewRef, inView] = useInViewHook(rootRef, padding, []);
return (
<div ref={rootRef}>
<div ref={inViewRef}>{inView && <p>I'm in view</p>}</div>
</div>
);
};
inViewRef
- ref to an element that should monitor whether it is in the viewport of mainWrapper or not.
rootRef
- ref to scrollable element that should listen to scroll event.
padding
- padding around the root.
Assign multiple refs to a component
You can wrap multiple ref
assignments in a single useCallback
:
import React, { useRef } from 'react';
import useInView from 'react-hook-simple-inview';
function MainComponent(props) {
const ref = useRef();
const [inViewRef, inView] = useInView(rootRef, 0, []);
const setRefs = useCallback(
(node) => {
ref.current = node;
inViewRef.current = node;
},
[inViewRef]
);
return (
<div ref={rootRef}>
<div ref={setRefs}>Shared ref is visible: {inView}</div>
</div>
);
}