Displaying all posts for specific Tag [Building Personal Blog Website Part 5]

Published on 9/8/2022, 12:00:00 AM

The blog post preview cards on your homepage display not only the cover, title and excerpt, but also a list of tags. It would be great if user could click on any of the tags and then see all blog posts connected to it. And that’s what you’ll implement today.

Let’s start with creating a new route in the Next.js application. Create a new folder tag in your pages directory. Inside create a file [tag].js - the goal is to have a route like YOUR_URL/tag/tag-name.

Blog-5-1.png

Now inside this [tag].js file you have to implement getStaticPaths and getStaticProps similarly to the Blog Post page.

For getStaticPaths you need to get a list of all tags that your CMS has:

export async function getStaticPaths() {
  const { data } = await client.query({
    query: gql`
      query Tags {
        tags {
          data {
            attributes {
              tagId
            }
          }
        }
      }
    `,
  });
  return {
    paths: data.tags.data.map((item) => ({
      params: { tag: item.attributes.tagId },
    })),
    fallback: false,
  };
}

In getStaticProps you’ll get all of the posts with specific tag:

export async function getStaticProps({ params }) {
  const { data } = await client.query({
    query: gql`
      query Tags {
        tags (
          filters: { tagId: { eq: "${params.tag}" } }
        ) {
          data {
            attributes {
              name
              tagId
              posts {
                data {
                  attributes {
                    title
                    slug
                    excerpt
					publishedAt
                    cover {
                        data {
                            attributes {
                                url
                            }
                        }
                    }
                    tags {
                        data {
                            attributes {
                                tagId
                                name
                            }
                        }
                    }
                  }
                }
              }
            }
          }
        }
      }
    `,
  });

  return {
    props: {
      tagData: data.tags.data[0],
    },
  };
}

And with that out of the way you will display the results in a similar manner as on the homepage:

export default function Tag({ tagData }) {
  return (
    <section className="my-8 mx-4">
      <h2 className="font-mono text-black text-xl md:text-4xl text-center mb-8">
        Articles with &quot;{tagData.attributes.name}&quot; tag
      </h2>
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4 ">
        {tagData.attributes.posts.data.map((post) => (
          <BlogPostPreview key={post.attributes.slug} post={post} />
        ))}
      </div>
    </section>
  );
}

Most of your work is already done, but you have one more thing to do - hook up this newly created page with Tags on the BlogPostPreview. Adjust components/BlogPostPreview.jsx - instead of a blank <a href=”#”> use the following next/link:

<div className="px-6 pt-4 pb-2">
        {post.attributes.tags.data.map((tag) => (
          <Link
            href={`/tag/${tag.attributes.tagId}`}
            key={tag.attributes.tagId}
          >
            <a>
              <span className="inline-block bg-gray-200 rounded-full px-3 py-1 text-sm font-semibold text-gray-700 mr-2 mb-2">
                {tag.attributes.name}
              </span>
            </a>
          </Link>
        ))}
      </div>

Now rebuild your app and open it in dev mode:

yarn build
yarn dev

Open your blog and click on any Tag. It should open a list of blog posts with this tag:

Blog-5-2.png

Last thing to do is to make this change live on Netlify. Commit all of your changes and push it to GitHub. Netlify will rebuild your app and in a few minutes you’ll be able to use your new feature online. Well done!

Get in touch

You can find me and contact me the following ways: