티스토리 뷰

NextJS

[NextJS] Routing

BIBLIYA 2022. 10. 14. 11:49

Routing

components/NavBar.js

import Link from "next/link";

export default function NavBar() {
  return (
    <nav>
      <Link href="/">Home</Link>
      <Link href="/about">About</Link>
    </nav>
  );
}

pages/index.js

import NavBar from "../components/NavBar";

export default function Home() {
  return (
    <div>
      <NavBar />
      <h1>Hello</h1>
    </div>
  );
}

 

useRouter()

import Link from "next/link";
import { useRouter } from "next/router";

export default function NavBar() {
    const router = useRouter();
    // useNavigate 같은 역할인듯?

  return (
    <nav>
      <Link href="/">
        <a style={{ color: router.pathname === "/" ? "red" : "blue" }}>Home</a>
      </Link>
      <Link href="/about">
        <a style={{ color: router.pathname === "/about" ? "red" : "blue" }}>About</a>
      </Link>
    </nav>
  );
}

 

 

<Link> tag를 썼음에도 불고 하고 <a> 태그로 문자열을 감싸주는 이유가 뭘까?

1. Link 태그에 그냥 문자열을 넣었을 경우 자동으로 a태그로 감싸주는데

이 기능 지원을 곧 중단할 거기 때문에 a태그를 넣어서 만드는 게 더 안전하다.

  • Deprecated. Warning shown by propType check. If the children provided is a string (example) we wrap it in an tag

2. 태그 없이는 style이나 className을 줄 수 없다.

'NextJS' 카테고리의 다른 글

[NextJS] _app  (0) 2022.10.14
[NextJS] Styles JSX  (0) 2022.10.14
[NextJS] CSS Modules  (0) 2022.10.14
[NextJS] Pages / Static Pre Rendering  (0) 2022.10.14
[NextJS] 라이브러리(Library) / 프레임워크(framework)  (0) 2022.10.14
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2026/04   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30
글 보관함