Skip to content

Instantly share code, notes, and snippets.

@kasperaamodt
Last active January 10, 2022 11:31
Show Gist options
  • Save kasperaamodt/055c6203d8761b4500c5fb108f0e4f03 to your computer and use it in GitHub Desktop.
Save kasperaamodt/055c6203d8761b4500c5fb108f0e4f03 to your computer and use it in GitHub Desktop.
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