Routing: Dynamic Routes | Next.js

Dynamic Routes can be used to programmatically generate route segments from dynamic data.

nextjs.org

 

 

 


App route 설정하기

 

- 우선 Next 프레임워크를 설치해준다.

npx create-next-app@latest

 

- 대부분 설정을 'yes' 하고 진행하였다.

 

 

 

 

- [폴더명] 안에 파일

  -page.js 화면을 구성

  -layout.js 화면을 감싸는 레이아웃

 

- Next에선, app> [폴더명] > page.js 로 구성해주면 ,
해당 경로로 라우터가 생성된다. 

 

ex )  example.com/[폴더명]

 

 

 

 

 


 

동적 라우트 설정

- dogs/[slug]/page.js

import Image from "next/image";

async function getData(slug: string) {
  const res = await fetch(`https://dog.ceo/api/breed/${slug}/images`);

  if (!res.ok) {
    throw new Error("Failed to fetch data");
  }
  return res.json();
}

export default async function Page({ params }: { params: { slug: string } }) {
  const data = await getData(params.slug);
  
//품종에 따른 강아지 사진들을 가져와서 사진을 띄운다.
  return (
    <main className="flex min-h-screen flex-col items-center justify-between p-24">
      <h1>{params.slug}</h1>

      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        {data.message.slice(0, 25).map((imgurl: string) => (
          <Image
            className="rounded-lg transition-transform duration-500 hover:border-2 hover:border-black"
            key={imgurl}
            src={imgurl}
            width={500}
            height={500}
            layout="responsive"
            objectFit="cover"
            alt="Picture of the dog"
            placeholder="blur"
            blurDataURL="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mPMqAcAAVUA6UpAAT4AAAAASUVORK5CYII="
          />
        ))}
      </div>
    </main>
  );
}

 

- 경로 폴더 명은 [slug] 로 지정해주면   example/dog/[임의의 값]

- 하위 페이지에 params로 임의의 값이 매개변수로 전달된다.

 

* placeholder='blur' 과 blurDataURL 에 크기가 작은 base64 이미지를 적용시키면,

이미지를 불러올때, placeHolder를 적용시켜준다.

 

 

 

https://png-pixel.com/

 

Transparent PNG Pixel Base64 Encoded

Embed PNG pixels directly in your source code If you don't like having small 1x1 pixel images in your projects, you can embed the base64 encoded pixel directly in your css or html source files. CSS background-image: url(data:image/png;base64,); HTML <img s

png-pixel.com

 

https://nextjs.org/docs/app/api-reference/components/image#blurdataurl

 

Components: <Image> | Next.js

Optimize Images in your Next.js Application using the built-in `next/image` Component.

nextjs.org


Next Image

 

import Image from 'next/image'

 

- Next 내장 컴포넌트 <Image>를 사용해줬다.

 

- Next Image 장점

  • 크기 최적화
  • 시각적 안정성
  • 빠른 페이지 로딩

 

 

 

 

+ Recent posts