Skip to content

<NextLink /> abstraction

Simplifying the use of next-link

React
NextLink.tsx
import NextLink, {LinkProps} from 'next/link';
import {useRouter} from 'next/router';
 
interface ActiveLinkProps extends LinkProps {
  activeClassName?: string;
  className?: string;
}
 
export function Link({
  href,
  children,
  className: targetClassName = '',
  activeClassName,
  prefetch = false,
  ...props
}: React.PropsWithChildren<ActiveLinkProps>) {
  const {asPath} = useRouter();
  const className =
    targetClassName +
    (asPath === href && activeClassName ? ' ' + activeClassName : '');
 
  return (
    <NextLink href={href} {...props} className={className} prefetch={prefetch}>
      {children}
    </NextLink>
  );
}

Usage

React
pages/index.tsx
<Link
  href={`${TEAMMATES_PAGE}/${teammate.id}`}
  className="text-blue-400 text-xs p-2 bg-blue-50 hover:bg-blue-100 rounded-md inline-flex items-center"
  activeClassName="underline"
>
  View more
  <ChevronRightIcon className="h-3 w-3" />
</Link>