NavLink コンポーネント

リンクにactive状態を追加したい場合は、このソリューションを使用できます。NavLink コンポーネントは、Qwik の<Link>コンポーネントを拡張し、以下の機能を追加します。

  • アクティブ状態: リンクの href が現在の URL パス名と一致する場合にクラスを適用します。

これにより、ナビゲーションのアクティブ状態をスタイリングできます。

動作原理

内部的には、NavLink はuseLocationフックを使用してナビゲーションの状態を取得します。リンクの href が現在の URL パス名と一致するかどうかをチェックして、activeClass を設定します。これにより、NavLink はナビゲーションに基づいてアクティブ状態を自動的に認識できます。

import { Slot, component$ } from '@builder.io/qwik';
import { Link, useLocation, type LinkProps } from '@builder.io/qwik-city';
 
type NavLinkProps = LinkProps & { activeClass?: string };
 
export const NavLink = component$(
  ({ activeClass, ...props }: NavLinkProps) => {
    const location = useLocation();
    const toPathname = props.href ?? '';
    const locationPathname = location.url.pathname;
 
    const startSlashPosition =
      toPathname !== '/' && toPathname.startsWith('/')
        ? toPathname.length - 1
        : toPathname.length;
    const endSlashPosition =
      toPathname !== '/' && toPathname.endsWith('/')
        ? toPathname.length - 1
        : toPathname.length;
    const isActive =
      locationPathname === toPathname ||
      (locationPathname.endsWith(toPathname) &&
        (locationPathname.charAt(endSlashPosition) === '/' ||
          locationPathname.charAt(startSlashPosition) === '/'));
 
    return (
      <Link
        {...props}
        class={`${props.class || ''} ${isActive ? activeClass : ''}`}
        
      >
        <Slot />
      </Link>
    );
  }
);

使用方法

activeClassプロップを追加して NavLink を使用できます。

import { component$ } from '@builder.io/qwik';
import { NavLink } from '..';
 
export default component$(() => {
  return (
    <>
      Links
      <div>
        <NavLink href="/docs" activeClass="text-green-600">
          /docs
        </NavLink>
      </div>
      <div>
        <NavLink
          href="/demo/cookbook/nav-link/example/"
          activeClass="text-green-600"
        >
          /demo/cookbook/nav-link/example/
        </NavLink>
      </div>
    </>
  );
});

Tailwind

Tailwind CSS を使用している場合は、tailwind 設定ファイルを編集し、エクスポートにimportant=trueを追加し、アクティブなリンクの際に重要になるように使用する CSS クラスの前に!を追加してください (例: activeClass="!text-green-600")。

コントリビューター

このドキュメントの改善に貢献してくれたすべてのコントリビューターに感謝します!

  • Adbib