Link 태그 이용하여 네비게이션 만들기

송민경's avatar
Aug 22, 2024
Link 태그 이용하여 네비게이션 만들기

1. <Link> 이용

import Link from "next/link" export default function Navigation(){ return (<nav> <ul> <li> <Link href="/">Home</Link> </li> <li> <Link href="/about-us">About Us</Link> </li> </ul> </nav> ); }
 

2. 페이지에 네비게이션 추가하기

import Navigation from "./components/navigation"; export default function Page(){ return ( <div> <Navigation /> <h1>Hello</h1> </div>); }
notion image
import Navigation from "../components/navigation"; export default function AboutUs() { return ( <div> <Navigation /> <h1>About Us</h1> </div> ); }
notion image
import Navigation from "./components/navigation"; export default function NotFound(){ return( <div> <Navigation /> <h1>Not Found</h1> </div> ); }
 
notion image

3. 사용자 경로 만들어 적용하고 콘솔에 표시하기

  • usePathname hook 사용시 오류남
import Link from "next/link" import { usePathname } from "next/navigation"; export default function Navigation(){ const path = usePathname(); console.log(path); return (<nav> <ul> <li> <Link href="/">Home</Link> </li> <li> <Link href="/about-us">About Us</Link> </li> </ul> </nav> ); }
notion image
💡
이 컴포넌트는 usePathname을 필요 usePathname은 클라이언트 컴포넌트에서만 작동 부모들이 모두 "use client"로 표시되어 있지 않으므로 기본적으로 서버 컴포넌트
"use client" import Link from "next/link" import { usePathname } from "next/navigation"; export default function Navigation(){ const path = usePathname(); console.log(path); return (<nav> <ul> <li> <Link href="/">Home</Link> </li> <li> <Link href="/about-us">About Us</Link> </li> </ul> </nav> ); }
notion image
notion image
notion image
 
 

4. 해당 페이지에서만 이모티콘 사용하기

"use client" import Link from "next/link" import { usePathname } from "next/navigation"; export default function Navigation(){ const path = usePathname(); return (<nav> <ul> <li> <Link href="/">Home</Link><Link href="/">Home</Link>{path === "/" ? "🔥" : ""} </li> <li> <Link href="/about-us">About Us</Link><Link href="/">Home</Link>{path === "/about-us" ? "🔥" : ""} </li> </ul> </nav> ); }
notion image
notion image
 
Share article

vosw1