Last active
January 10, 2022 11:31
-
-
Save kasperaamodt/055c6203d8761b4500c5fb108f0e4f03 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Image from "next/image"; | |
import ErrorPage from "next/error"; | |
import { useRouter } from "next/router"; | |
import { getAllPostSlugs, getPostAndMorePosts } from "../../lib/api"; | |
import parse, { domToReact } from "html-react-parser"; | |
export default function Blog({ blog }) { | |
const router = useRouter(); | |
if (!router.isFallback && !blog?.slug) { | |
return <ErrorPage statusCode={404} />; | |
} | |
const replaceImage = { | |
replace: ({ name, attribs, children }) => { | |
if (name === "figure" && /wp-block-image/.test(attribs.class)) { | |
return <>{domToReact(children, replaceImage)}</>; | |
} | |
if (name === "img") { | |
return ( | |
<Image | |
src={attribs.src} | |
width={attribs.width} | |
height={attribs.height} | |
alt={attribs.alt ? attribs.alt : "Blog post image"} | |
/> | |
); | |
} | |
} | |
}; | |
return ( | |
<> | |
{router.isFallback ? ( | |
<span>Loading…</span> | |
) : ( | |
<> | |
<h1>{blog.title}</h1> | |
<div> | |
{parse(blog.content, replaceImage)} | |
</div> | |
</> | |
)} | |
</> | |
); | |
} | |
export async function getStaticProps({ params }) { | |
const data = await getPostAndMorePosts(params.slug); | |
return { | |
props: { | |
blog: data.post | |
} | |
}; | |
} | |
export async function getStaticPaths() { | |
const allPosts = await getAllPostSlugs(); | |
return { | |
paths: allPosts.edges.map(({ node }) => `/blog/${node.slug}`) || [], | |
fallback: true | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment