Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ManiruzzamanAkash/509104ec1dd6d54c920a7e5aa6d1ad0b to your computer and use it in GitHub Desktop.
Save ManiruzzamanAkash/509104ec1dd6d54c920a7e5aa6d1ad0b to your computer and use it in GitHub Desktop.
Post list and detail page with Next JS static site props and staticpaths
// pages/posts/index.jsx
import Head from "next/head";
import Link from "next/link";
export default function PostsPage({ posts }) {
return (
<>
<Head>
<title>DevsEnv | Posts</title>
<meta name="description" content="DevsEnv tutorials Posts" />
<meta name="keyword" content="DevsEnv, tutorials, devsenv about us" />
</Head>
<h2>All Posts</h2>
<hr />
{
posts.map((post) => (
<div key={post.id}>
<h2>{post.title}</h2>
<p>{post.body}</p>
<Link href={`/posts/${post.id}`}>
View details
</Link>
<hr />
</div>
))
}
</>
)
}
export async function getStaticProps() {
const res = await fetch('https://jsonplaceholder.typicode.com/posts')
const posts = await res.json()
return {
props: {
posts,
},
}
}
// pages/posts/[id].jsx
import Head from "next/head";
export default function PostDetailPage({ post }) {
return (
<>
<Head>
<title>DevsEnv | Posts</title>
<meta name="description" content="DevsEnv tutorials Posts" />
<meta name="keyword" content="DevsEnv, tutorials, devsenv about us" />
</Head>
<div key={post.id}>
<h2>{post.title}</h2>
<p>{post.body}</p>
</div>
</>
)
}
export async function getStaticProps(context) {
const { params } = context;
const { id } = params;
const res = await fetch(`https://jsonplaceholder.typicode.com/posts/${id}`);
const post = await res.json();
return {
props: {
post,
},
};
}
export async function getStaticPaths() {
if (process.env.SKIP_BUILD_STATIC_GENERATION) {
return {
paths: [],
fallback: 'blocking',
}
}
const res = await fetch('https://jsonplaceholder.typicode.com/posts');
const posts = await res.json();
const paths = posts.map((post) => ({
params: { id: post.id + '' },
}))
return { paths, fallback: false }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment