QDD 1-3. useRouter, API Routes, getStaticProps, getStaticPaths

2023. 4. 27.·👨‍💻 프로젝트 경험/Toy

📍Q8. 특정 URL에서만 특정 컴포넌트를 렌더링하려면?

✅Next.js의 useRouter 훅을 사용

- React 훅이므로 컴포넌트 내부에서만 사용 가능!

- 사용 전에 아래 처럼 선언 필요

import { useRouter } from 'next/router'

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

 

router 객체의 pathname, asPath, route 프로퍼티를 이용하면 현재 페이지의 파라미터를 받을 수 있다

query 프로퍼티를 이용하면 query string도 받을 수 있다

 

이를 통해 특정 페이지에서 원하는 컴포넌트를 렌더링 할 수 있다

 

📍Q9. Next.js 에서 API를 만드려면?

pages/api 폴더 내의 파일들은 /api/* 에 매핑되며 페이지 대신 API 엔드 포인트로  처리된다

- sever-side 로만 작동하며 client-side 번들 크기를 늘리지 않는다

 

pages/api/user.ts 를 아래처럼 만들고

export default (req, res) => {
  res.status(200).json({ name: "John Doe" });
}

 

app에서 /api/user 에 접속하면, {"name":"John Doe"} 를 response로 띄워준다

 

pages/api/forums/[forumsId].ts 파일을 만들고, api를 만든다

import type { NextApiRequest, NextApiResponse } from "next";
const { forums } = require("./data");

interface ForumType {
  id: string;
  name: string;
  place: string;
  address: string;
  host: string;
  date: string;
  time: string;
  description: string;
  image: string;
}

interface ErrorType {
  message: string;
}

export default (
  req: NextApiRequest,
  res: NextApiResponse<ForumType[] | ErrorType>,
) => {
  const forum = forums.filter((item) => item.id === req.query.forumId);

  if (req.method === "GET") {
    res.status(200).json(forum);
  } else {
    res.setHeader("Allow", ["GET"]);
    res.status(405).json({ message: `Method ${req.method} is not allowed` });
  }
};

그리고, req.query.forumId 를 통해 쿼리 파라미터를 받을 수 있다

 

📍Q10. 다이나믹 라우팅 사용 시 페이지 경로를 미리 생성하려면?

✅getStaticPaths 를 사용하여, 지정된 모든 page path를 정적으로 프리렌더링할 수 있다

- getStaticPaths를 사용하려면 getStaticProps도 사용해야 한다
- fallback을 설정할 수 있다 (디폴트 : false => 404 page로 연결)

 

📍참고

 

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

 

https://nextjs.org/docs/api-routes/introduction

 

API Routes: Introduction | Next.js

Next.js supports API Routes, which allow you to build your API without leaving your Next.js app. Learn how it works here.

nextjs.org

 

https://nextjs.org/docs/basic-features/data-fetching/get-static-paths

 

Data Fetching: getStaticPaths | Next.js

Fetch data and generate static pages with `getStaticProps`. Learn more about this API for data fetching in Next.js.

nextjs.org

 

'👨‍💻 프로젝트 경험/Toy' 카테고리의 다른 글
  • QDD 1-4. Strapi Headless CMS 및 Cloudinary로 백엔드 구성하기
  • QDD 1-2. Next.js pages 기능 & Styled-components 규칙
  • QDD 1-1. Yarn Berry & Next.js 설치, ESLint & Prettier 설치
  • QDD 1-0. Intro: Academia
지식물원
지식물원
지식이 자라는 식물원!
  • 지식물원
    지식물원
    지식물원
  • 전체
    오늘
    어제
    • 분류 전체보기 (516)
      • 🎨 프론트엔드 공부 (253)
        • JS & TS (92)
        • HTML & CSS (22)
        • React & Next (49)
        • Vue & Nuxt (22)
        • 기타 (68)
      • 🤓 기술 학습 & 공부 기록 (116)
        • Node.js (0)
        • Python (37)
        • 백엔드 (0)
        • 딥러닝 (1)
        • 컴퓨터 일반 (72)
        • 개발 인프라 (6)
      • 👨‍💻 프로젝트 경험 (6)
        • Work (0)
        • Toy (6)
      • ⚙️ 개발 팁 & 노하우 (21)
        • 프론트엔드 (6)
        • 기타 (15)
      • ☕️ 커리어 & 인터뷰 준비 (88)
        • 코딩 테스트 (88)
      • 📰 기술 트렌드 & 생각 정리 (4)
      • 📚 기타 (25)
        • 마케팅 (15)
        • 비개발서적 (10)
  • 블로그 메뉴

    • 태그
  • 링크

  • 공지사항

    • 모바일 접속 시 코드 하이라이팅 깨질 때
  • 인기 글

  • hELLO· Designed By정상우.v4.10.3
지식물원
QDD 1-3. useRouter, API Routes, getStaticProps, getStaticPaths
상단으로

티스토리툴바