npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

react-use-anchor

v1.1.8

Published

`useAnchor` is a custom React hook that creates dynamic anchor links for headings in your content. It leverages the Intersection Observer API to detect which headings are currently visible in the viewport, making it ideal for building table of contents or

Downloads

258

Readme

useAnchor

useAnchor is a custom React hook that creates dynamic anchor links for headings in your content. It leverages the Intersection Observer API to detect which headings are currently visible in the viewport, making it ideal for building table of contents or navigation systems for long-form content.

Installation

npm i react-use-anchor@latest

🚀 Advantages

  • Ultra-Lightweight & Simple: Just one hook—no complex setup or required parameters! ⚡
  • Style Freedom: No predefined styles, giving you the power to craft your own design. 🎨
  • Zero Dependencies: Built solely on the native Intersection Observer API, keeping it clean and efficient. 📦
  • Fully Customizable: Tailor the heading tags and observer options to fit your exact needs. 🛠️
  • Dynamic Updates: Automatically responds as you scroll, providing a seamless experience. 🔄

Usage

Here's a basic example of how to use the useAnchor hook: Open in StackBlitz Open in StackBlitz

"use client";

import useAnchor from "react-use-anchor";

export default function MyComponent() {
  const [containerRef, visibleIds, allAnchors] = useAnchor();

  return (
    <div className="flex justify-evenly w-screen">
      <div>
        <nav className="sticky top-0 flex flex-col gap-4">
          {allAnchors.map((heading) => (
            <a
              key={heading.id}
              href={`#${heading.id}`}
              /* Multiple sections may be visible in the viewport simultaneously.
                The visibleIds array is ordered according to their position from top to bottom.
                Therefore, visibleIds[0] will always represent the first section visible in the viewport.
              */
              className={`${
                visibleIds[0] === heading.id ? "text-red-500" : "text-white"
              }`}
            >
              {heading.title}
            </a>
          ))}
        </nav>
      </div>

      <div ref={containerRef} className="flex flex-col gap-4 space-y-96">
        <h2 id="section1">Section 1</h2>
        <p>Content for section 1...</p>
        <h2 id="section2">Section 2</h2>
        <p>Content for section 2...</p>

        <h2 id="section3">Section 3</h2>
        <p>Content for section 3...</p>
        <h2 id="section4">Section 4</h2>
        <p>Content for section 4...</p>
        {/* More sections... */}
      </div>
    </div>
  );
}

API

useAnchor({options, heading})

The useAnchor hook accepts an IntersectionObserverOptions and a heading tag and returns an array with three elements:

containerRef: A ref object to be attached to the container of your content. visibleIds: An array of IDs of the currently visible headings, sorted by their position in the viewport. allAnchors: An array of all heading IDs and text content in the order they appear in the document.

Options

The hook accepts the following parameters:

type TUseAnchor = {
  heading?: "h1" | "h2" | "h3" | "h4" | "h5";
  options?: IntersectionObserverOptions;
};

interface IntersectionObserverOptions {
  root?: Element | null;
  rootMargin?: string;
  threshold?: number | number[];
}

heading (optional): The heading tag to observe. Default is 'h2'. Can be 'h1', 'h2', 'h3', 'h4', or 'h5'.

options (optional): An object with Intersection Observer options:

  • root: The root element to use as the viewport. Default is the browser viewport.
  • rootMargin: Margin around the root element. Default is '0px'.
  • threshold: A number or array of numbers indicating at what percentage of the target's visibility the observer's callback should be executed. Default is 0.

How It Works

The hook creates an Intersection Observer to watch for heading elements that enter or leave the viewport. It attaches this observer to all heading elements (of the specified type) within the container element. As headings become visible or hidden, the hook updates its state. The hook returns both the currently visible heading IDs and all heading IDs, allowing you to create dynamic navigation that highlights the current section.

Best Practices

Ensure that all your observed heading elements have unique id attributes. Attach the containerRef to the parent element that contains all your headings. Use the visibleIds array to highlight the currently visible sections in your navigation. Use the allAnchors array to create a complete list of all sections.

Troubleshooting

If you're not seeing any IDs in the visibleIds or allAnchors arrays:

Make sure your heading elements have id attributes. Check that you're using the correct heading type (e.g., 'h2' if that's what you specified in the options). Ensure that the containerRef is correctly attached to the parent element of your headings.

If you encounter any issues or have questions, please open an issue on the GitHub repository.

License

This project is licensed under the MIT License.