Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Including inline images in Sanity's block content with Next.js's next/image
/** @jsx jsx */
import sanityClient from '../../client'
import { jsx } from 'theme-ui'
import BlockContent from '@sanity/block-content-to-react'
import Layout from '../../components/layout'
import Link from 'next/link'
import { useRouter } from 'next/router'
import Image from 'next/image'
import imageUrlBuilder from '@sanity/image-url'
const builder = imageUrlBuilder(sanityClient)
function urlFor(source) {
return builder.image(source)
}
const serializers = {
types: {
image: props =>
(
<div sx={{
maxWidth: '100%',
margin: '0 auto',
height: 'auto',
display: 'block',
'& > div ': {
position: 'relative !important',
height: 'auto',
display: 'block',
},
'& > div > img': {
height: '100% !important',
width: '100% !important',
position: 'relative !important',
}
}}>
<Image src={urlFor(props.node.asset).url()} layout="fill" objectFit="contain" />
<p sx={{
textAlign: 'center',
}}>{props.node.caption}</p>
</div >
)
}
}
const Post = ({ post, data }) => {
const router = useRouter()
if (router.isFallback) {
return (
<Layout title={data?.[0]?.title ?? "Jennifer K Shields"} >
<div>Loading...</div>
</Layout>
)
}
return (
<Layout title={data[0].title} intro={data[0].intro}>
<div sx={{
m: 4,
}}>
{post.link ? (
<h2 sx={{
'@media (min-width: 800px)': {
fontSize: 6,
}
}}><a href={post.link}>{post.title} -></a></h2>
) : (
<h2>{post.title}</h2>
)
}
{post.body ? (
<BlockContent blocks={post.body} serializers={serializers} />
) : (
<BlockContent blocks={post.excerpt} />
)
}
<div sx={{
textAlign: 'right',
}}>{post.date}</div>
<div>
<Link href="/"><a>Back home -></a></Link>
</div>
</div>
</Layout>
)
}
export default Post
export const getStaticPaths = async () => {
const posts = await sanityClient.fetch(`*[_type == "blog"]{ slug }`)
const paths = posts.map(post => ({
params: {
slug: post.slug.current,
id: post.slug.current
}
}))
return {
paths,
fallback: true
}
}
export const getStaticProps = async ({ params }) => {
const post = await sanityClient.fetch(`*[_type == "blog" && slug.current == $slug]{ title, date, link, excerpt, body, slug }[0]`, { slug: params.slug })
const data = await sanityClient.fetch(`*[_type == "siteSettings"]{ title, intro }`);
return {
props: { post, data },
revalidate: 30,
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment