Making use of "ActiveLink" component in NextJS

65 Views Asked by At

I am now reading this page: https://nextjs.org/docs/pages/api-reference/functions/use-router and it contains this chunk of code.

import { useRouter } from 'next/router'

function ActiveLink({ children, href }) {
  const router = useRouter()
  const style = {
    marginRight: 10,
    color: router.asPath === href ? 'red' : 'black',
  }

  const handleClick = (e) => {
    e.preventDefault()
    router.push(href)
  }

  return (
    <a href={href} onClick={handleClick} style={style}>
      {children}
    </a>
  )
}

export default ActiveLink

What I want is some sample code that shows how to use this ActiveLink component.

Is there some site or blog on the net where I could find that ?

2

There are 2 best solutions below

1
On

You can test and render this reusable react component online in a simple nextjs codesandbox or in your local machine like this :

<ActiveLink href="/link-url">Link Label</ActiveLink>

Here is an article about how to render react components in general .

1
On
"use client";
 
import Link from "next/link";
import { usePathname } from "next/navigation";
 
import { cn } from "~/utils/cn";
 
interface Props extends React.ComponentPropsWithoutRef<typeof Link> {
  className?: string;
  activeClassName?: string;
}
 
export const ActiveLink = (props: Props) => {
  const pathname = usePathname();
  const isActive = pathname === props.href;
  const activeClassName = props.activeClassName ?? "text-red-500";
 
  return (
    <Link
      {...props}
      className={cn(props.className, isActive && activeClassName)}
    />
  );
};