Skip to content

Commit

Permalink
タグごとのページを追加
Browse files Browse the repository at this point in the history
  • Loading branch information
miketako3 committed Sep 30, 2022
1 parent 5189445 commit 06a5fbf
Show file tree
Hide file tree
Showing 3 changed files with 84 additions and 1 deletion.
2 changes: 1 addition & 1 deletion components/post-header.tsx
Expand Up @@ -21,7 +21,7 @@ const PostHeader = ({ title, coverImage, date, author, tags }: Props) => {
</div>
<ul className="flex gap-x-2">
{
tags.map((tag) => <li className="font-bold mb-12">{tag}</li>)
tags.map((tag) => <li className="font-bold mb-12"><a href={`/tags/${tag}`}>{tag}</a></li>)
}
</ul>
<div className="mb-8 md:mb-16 sm:mx-0">
Expand Down
16 changes: 16 additions & 0 deletions lib/api.ts
Expand Up @@ -45,3 +45,19 @@ export function getAllPosts(fields: string[] = []) {
.sort((post1, post2) => (post1.date > post2.date ? -1 : 1))
return posts
}

export function getPostsByTag(tag: string, fields: string[] = []) {
const slugs = getPostSlugs()
return slugs
.map((slug) => getPostBySlug(slug, fields))
.filter((post) => post.tags.includes(tag))
.sort((post1, post2) => (post1.date > post2.date ? -1 : 1))
}

export function getAllTags() {
const allPostTags = getAllPosts(['tags'])
.flatMap((post) => post.tags)
.sort()

return Array.from(new Set(allPostTags))
}
67 changes: 67 additions & 0 deletions pages/tags/[tag].tsx
@@ -0,0 +1,67 @@
import {getAllTags, getPostsByTag} from "../../lib/api";
import Post from "../../interfaces/post";
import Head from "next/head";
import Layout from "../../components/layout";
import Container from "../../components/container";
import MoreStories from "../../components/more-stories";

type Props = {
posts: Post[],
tag: string
}

export default function Index({ posts, tag }: Props) {
return (
<>
<Layout>
<Head>
<title>Tag: {tag}</title>
</Head>
<Container>
<MoreStories posts={posts} />
</Container>
</Layout>
</>
)
}

type Params = {
params: {
tag: string
}
}


export const getStaticProps = ({ params }: Params) => {
const posts = getPostsByTag(params.tag, [
'title',
'date',
'slug',
'author',
'coverImage',
'excerpt',
'tags'
])

return {
props: {
posts: posts,
tag: params.tag
},
}
}

export function getStaticPaths() {
const tags = getAllTags();

return {
paths: tags.map((tag) => {
return {
params: {
tag: tag,
},
}
}),
fallback: false,
}
}

0 comments on commit 06a5fbf

Please sign in to comment.