Next JS

How to create a blog detail page or slug page in NextJS?

In Next.js, you can create a blog detail page or slug page by following these steps:

  1. Set up a Next.js project: If you haven’t already, create a new Next.js project using the appropriate commands or boilerplate setup.
  2. Create a new page: In the pages directory of your project, create a new file with the naming convention [slug].js. For example, you can name it slug.js or blog/[slug].js. This will create a dynamic route where the slug parameter can be passed in the URL.
  3. Define the page component: In the newly created file, you can define the page component for the blog detail page. You can use functional components or class components as per your preference. For this example, let’s use a functional component:

import { useRouter } from ‘next/router’;
export default function BlogDetail() {
const router = useRouter();
const { slug } = router.query;
return (
<div>
<h1>Blog Detail Page</h1>
<p>Slug: {slug}</p>
{/* Fetch and display blog details using the slug */}
</div>

);
}

In this example, we import the useRouter hook from Next.js, which provides access to the router object. We then use router.query.slug to extract the slug parameter from the URL.

  1. Fetch and display blog details: Within the page component, you can fetch the blog details using the slug parameter and display the relevant information. This typically involves making an API call to retrieve the blog content from a database or an external source.
  2. Link to the blog detail page: In your blog listing page or wherever you generate links to individual blog posts, use the Link component from Next.js to create links to the dynamic blog detail page. For example:
import Link from 'next/link';
export default function BlogListing({ blogs })
{
return (
<div>
<h1>Blog Listing Page</h1>
<ul>
{blogs.map(blog => (
<li key={blog.id}>
<Link href={`/blog/${blog.slug}`}>
<a>{blog.title}</a>
</Link>
</li>
))}
</ul>
</div>
);
}

In this example, we assume you have an array of blog objects with id, title, and slug properties. We map over the blogs array and generate links using the Link component, providing the appropriate slug in the href attribute.

That’s it! With these steps, you can create a blog detail page or slug page in Next.js. Remember to customize the component and API calls based on your specific requirements.

 

 

Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *

five × two =

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top