본문 바로가기

Web/Next

[Next] <Link> 태그 passHref 속성 이해하기

왜 passHref가 필요한가?

passHref는 Next.js의 Link 컴포넌트가 생성하는 href prop을 자식 컴포넌트에게 전달하는 역할을 합니다.

  1. SEO 최적화: 검색 엔진이 링크를 올바르게 인식할 수 있습니다.
  2. 브라우저 기능: 우클릭 메뉴의 "새 탭에서 열기" 등이 정상 작동합니다.

 

passHref가 필요한 경우

1. Link 내부에 커스텀 컴포넌트나 button을 사용할 때

가장 대표적인 경우입니다. Link 안에 <a> 태그가 아닌 다른 커스텀 컴포넌트를 넣을 때 passHref가 필요합니다.

// ❌ 잘못된 방법 - passHref 없이 사용
function ViewAllButton({ children = "전체보기", className, href, ...props }) {
  return (
    <Link href={href}>
      <button className={className} {...props}>
        {children}
      </button>
    </Link>
  );
}

// ✅ 올바른 방법 - passHref 사용
function ViewAllButton({ children = "전체보기", className, href, ...props }) {
  return (
    <Link href={href} passHref>
      <button
        className={cn(
          "py-[15.5px] border-1 cursor-pointer border-Gray-100 px-[200.5px] text-body-02 font-semibold text-Dark-Gray",
          className
        )}
        {...props}
      >
        {children}
      </button>
    </Link>
  );
}