Next.JS - 2. Layout, Head, rewrites

CodeModel·2023년 4월 9일
0

Next.JS

목록 보기
2/4

Layout

보통 _app.js 파일에 많은 코드가 들어가지 않는것을 원해서 컴포넌트를 분리한다.

Layout.js

export default function Layout({ children }) {
  return (
    <>
      <NavBar />
      <div>{children}</div> // childeren은 Layout 컴포넌트가 감싼 컴포넌트를 가져온다.
    </>
  );
}

next.js가 가지고 있는 작은 패키지 기능이다. Head를 손쉽게 만들 수 있게 한다.

import Head from "next/head";

로딩 화면 나타내기

{!movies && <h4>Loading...</h4>}

데이터가 없을 때 오류 안나오게 하기

movies?.map(()=>{})

movies라는 것은 처음에 빈 배열이 있어야 한다. 없으면 undifind 이기 때문이다. 하지만 ?를 붙이면 undifind일 때 map을 안하게 한다.

redirect

어떠한 url로 이동할 시 지정한 url로 이동하는 것을 의미한다.

async redirects() {
    return [
      {
        source: "/old-blog/:path*", // *은 모든 주소를 의미
        destination: "/new-blog/:path*",
        permanent: false,
      },
    ];
  },

old-blog의 어떠한 경로를 입력하던 new-blog의 경로로 이동하게된다.

rewrites

rewrites 는 특정한 url로 이동시키지만 url에 도메인은 바꾸지 않는다. 즉 API키를 숨길 수 있다는 것 이다.

async rewrites() {
    return [
      {
        source: "/api/movies",
        destination: `https://api.themoviedb.org/3/movie/popular?api_key=${API_KEY}`,
      },
    ];
  },
profile
개발자가 되기 위한 일기

0개의 댓글