@altano/use-visible-elements
TypeScript icon, indicating that this package has built-in type declarations

1.0.7 • Public • Published

use-visible-elements

npm Typed with TypeScript ESM only

React hook to faciliate observing the visibility of elements in a React tree, by selector.

Installation

npm install @altano/use-visible-elements

Example

Component.jsx

import { VisibleElementObserver, useVisibleElements } from "@altano/use-visible-elements";

function Component() {
  const visibleElements = useVisibleElements();
  React.useEffect(() => {
    console.log(`These elements are visible: `, visibleElements);
  }, [visibleElements]);
  return (
    <VisibleElementObserver selector="div.root > ul > li">
      <div className="root">
        <ul>
          <li>Some stuff</li>
          <li>Some more stuff</li>
        </ul>
      </div>
    </VisibleElementObserver>
  );
}

Notes:

  • Does not yet respond to DOM mutations. Observed tree must be statically mounted on first mount. Children can't be conditionally mounted. This could easily be added but this limitation is due to my only use of this hook being in a static site generator.
  • The useWrapperDiv prop can be used to suppress creating any DOM elements for the observation. useWrapperDiv={true} requires having a single child of <VisibleElementObserver> that accepts a ref.
  • Don't use this hook if you own the whole component tree. Use explicit refs instead. This should only be used when you don't own the tree (e.g. you're rendering Markdown MDX components on a static site).

Readme

Keywords

none

Package Sidebar

Install

npm i @altano/use-visible-elements

Weekly Downloads

4

Version

1.0.7

License

UNLICENSED

Unpacked Size

5.38 kB

Total Files

5

Last publish

Collaborators

  • altano