,

Part 5 of Next Js Bangla Tutorial: Exploring getStaticProps and getStaticPaths

Posted by

Next Js Bangla Tutorial: getStaticProps and getStaticPaths | Part 5

Next Js Bangla Tutorial: getStaticProps and getStaticPaths | Part 5

In this tutorial, we will learn about the getStaticProps and getStaticPaths methods in Next.js. These methods are used to fetch data at build time and generate static pages for dynamic routes.

getStaticProps

The getStaticProps method is used to fetch data at build time and pass it as props to the page component. This method is commonly used to fetch data from an API or database and pre-render static pages for dynamic routes.

getStaticPaths

The getStaticPaths method is used to specify dynamic routes to pre-render at build time. This method is commonly used in combination with getStaticProps to generate static pages for dynamic routes with varying data.

Example

      
        import React from 'react';
        
        export default function Post({ post }) {
          return (
            <div>
              <h1>{post.title}</h1>
              <p>{post.content}</p>
            </div>
          );
        }
        
        export async function getStaticPaths() {
          const res = await fetch('https://api.example.com/posts');
          const posts = await res.json();
          
          const paths = posts.map((post) => ({
            params: { id: post.id.toString() }
          }));
          
          return { paths, fallback: false };
        }
        
        export async function getStaticProps({ params }) {
          const res = await fetch(`https://api.example.com/posts/${params.id}`);
          const post = await res.json();
          
          return { props: { post } };
        }
      
    

In the example above, we have a page component that fetches post data using the getStaticProps method and specifies dynamic routes using the getStaticPaths method. This will pre-render static pages for each post at build time.

That’s it for our tutorial on getStaticProps and getStaticPaths in Next.js. These methods are powerful tools for generating static pages for dynamic routes and fetching data at build time.

0 0 votes
Article Rating
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@bamnishairf8984
6 months ago

vai apnar bujanu style very awesome