Navigation

LinkSection

Link to a section on the same page, with native scroll-spy

Preview

Introduction

Installation

Usage

Scroll inside the document: the browser marks the visible section by itself. scroll-target-group: auto on the list turns it on, Chromium only for now; active marks it by hand.

size
children
active

Code

import css from "./LinkSection.module.css";

type Size = "sm" | "md" | "lg";

interface ResponsiveSize {
  base: Size;
  mobile?: Size;
  tablet?: Size;
  desktop?: Size;
  wide?: Size;
}

interface LinkSectionProps {
  href: `#${string}`;
  size: Size | ResponsiveSize;
  active?: boolean;
  children: React.ReactNode;
}

function getSizeClasses(size: Size | ResponsiveSize): string {
  if (typeof size === "string") {
    return css[size];
  }

  const classes = [css[`${size.base}_base`]];

  if (size.mobile) classes.push(css[`${size.mobile}_mobile`]);
  if (size.tablet) classes.push(css[`${size.tablet}_tablet`]);
  if (size.desktop) classes.push(css[`${size.desktop}_desktop`]);
  if (size.wide) classes.push(css[`${size.wide}_wide`]);

  return classes.join(" ");
}

export default function LinkSection({
  href,
  size,
  active,
  children,
}: LinkSectionProps) {
  return (
    <a
      href={href}
      className={`
        ${css.link}
        ${getSizeClasses(size)}
        ${active ? css.active : ""}
      `}
      aria-current={active ? "location" : undefined}
    >
      {children}
    </a>
  );
}

Props

PropTypeRequiredDescription
href`#${string}`requiredAnchor of a section on the same page. The type rejects paths like "/about" at compile time.
size"sm" | "md" | "lg" | ResponsiveSizerequiredLink size (height and type). Fixed or responsive.
activeboolean—Marks the link as the current section by hand (aria-current="location", tinted background). With scroll-target-group: auto on the list (Chromium only for now), the browser paints the visible section by itself, without aria-current.
childrenReact.ReactNoderequiredLink content.