1.0.11 • Published 3 years ago

react-hook-simple-inview v1.0.11

Weekly downloads
-
License
MIT
Repository
github
Last release
3 years ago

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>
  );
}
1.0.11

3 years ago

1.0.9

3 years ago

1.0.10

3 years ago

1.0.8

3 years ago

1.0.7

3 years ago

1.0.6

3 years ago

1.0.5

3 years ago

1.0.4

3 years ago

1.0.3

3 years ago

1.0.2

3 years ago

1.0.1

3 years ago

1.0.0

3 years ago