nextjs create blog

nextjs

To create a blog with Next.js, you’ll need to create a page that displays a list of blog posts and a page that displays a single blog post.

Here’s an example of how you could create the list of blog posts page:

import Link from 'next/link'
import Layout from '../components/Layout'

function Blog({ posts }) {
  return (
    <Layout>
      <h1>Blog</h1>
      <ul>
        {posts.map(post => (
          <li key={post.id}>
            <Link href="/blog/[id]" as={`/blog/${post.id}`}>
              <a>{post.title}</a>
            </Link>
          </li>
        ))}
      </ul>
    </Layout>
  )
}

export async function getStaticProps() {
  // Get the posts from an API or a database
  const res = await fetch('https://my-api.com/posts')
  const posts = await res.json()

  return {
    props: {
      posts,
    },
  }
}

export default Blog

This page displays a list of blog posts, with each post linked to a single post page. The Link component is used to create the links, and the as prop is used to specify a custom URL for the link.

To create the single post page, you can create a dynamic route using a wildcard in the page file name. For example, create a file called [id].js in the blog directory with the following content:

import Layout from '../../components/Layout'

function BlogPost({ post }) {
  return (
    <Layout>
      <h1>{post.title}</h1>
      <p>{post.body}</p>
    </Layout>
  )
}

export async function getStaticPaths() {
  // Get the paths from an API or a database
  const res = await fetch('https://my-api.com/posts')
  const posts = await res.json()

  const paths = posts.map(post => `/blog/${post.id}`)

  return {
    paths,
    fallback: false,
  }
}

export async function getStaticProps({ params }) {
  // Get the post from an API or a database
  const res = await fetch(`https://my-api.com/posts/${params.id}`)
  const post = await res.json()

  return {
    props: {
      post,
    },
  }
}

export default BlogPost

This page displays a single blog post based on the id parameter in the URL. The getStaticPaths function is used to generate a list of paths for the dynamic route, and the getStaticProps function is used to fetch the data for the post.

With these two pages, you should have a basic blog application with Next.js. You can customize the layout and styling to fit your needs.