본문 바로가기
개발/Next.js

Next.js 는 폴더, 파일 이름이 엔드포인트

by 안뇽! 2022. 1. 18.
반응형

리액트는 라이브러리이기 때문에 동적 라우팅을 위해 외부 라이브러리인 react-router-dom 을 사용했다.

 

반면 프레임워크인 Next.js는 동적라우팅 기능이 이미 내장되어 있다.

 

신기하게도 폴더의 이름, 파일의 이름이 곧 api 혹은 params가 되는 것이다.

 

api 폴더의 hello.js
주소창에 폴더이름, 파일이름을 엔드포인트로 사용한다.

동적라우팅도 마찬가지이다.

pages 파일

pages파일을 위와 같이 구성하였다.

 

//pages/posts/[id].js
import { useRouter } from "next/router";

export default function Page() {
  const router = useRouter();
  console.log(router.query);
  const { id } = router.query;//id의 value가 엔드포인트가 된다. 
  return (
    <button type="button" onClick={() => router.push("/about")}>
      Click me {id}
    </button>
  );
}

posts폴더와 [id].js가 엔드포인트의 역할을 한다.

버튼을 클릭하면 아래 클릭이벤트에 의해 '/about'으로 이동한다.

  <button type="button" onClick={() => router.push("/about")}>
      Click me {id}
    </button>

 

 

전체 코드

https://github.com/ryu9663/next-js-practice

 


 

참고자료

https://nextjs.org/docs/api-reference/next/router

 

next/router | Next.js

Learn more about the API of the Next.js Router, and access the router instance in your page with the useRouter hook.

nextjs.org

 

반응형