I’m developing a blog on next.js with sanity.io, and I’m having trouble using the code-input plugin.
What I do have
I’m able to use the code component block on sanity, which looks something like this:
Everything good on the sanity side. My problem comes with using it on the next.js [slug].js
file.
This issue with this is that I don’t have a serializer.js file/component anywhere on my code, not even on the studio root folder. I’ve seen this applies for gatsby but I don’t know how to apply it for Next.js
This is what I currently Have:
JavaScript
x
70
70
1
import groq from 'groq'
2
import imageUrlBuilder from '@sanity/image-url'
3
import BlockContent from '@sanity/block-content-to-react'
4
import client from '../../client'
5
import Layout from '../../components/layout'
6
import utilStyles from '../../styles/utils.module.css'
7
import styles from '../../components/layout.module.css'
8
9
function urlFor (source) {
10
return imageUrlBuilder(client).image(source)
11
}
12
13
const Post = (props) => {
14
const {
15
title = 'Missing title',
16
name = 'Missing name',
17
categories,
18
authorImage,
19
mainImage,
20
code,
21
body = []
22
} = props
23
console.log(props)
24
return (
25
<Layout>
26
<article>
27
<div className={styles.container}>
28
<figure>
29
<img src={urlFor(mainImage).url()} />
30
</figure>
31
<h1 className={utilStyles.headingXl}>{title}</h1>
32
{categories && (
33
<ul className="inline">
34
Category:
35
{categories.map(category =>
36
<li key={category}>
37
<span className="inline-flex items-center justify-center px-2 py-1 text-xs font-bold leading-none text-indigo-100 bg-indigo-700 rounded">{category}</span>
38
</li>)}
39
</ul>
40
)}
41
<BlockContent
42
blocks={body}
43
imageOptions={{fit: 'max'}}
44
{client.config()}
45
{code}
46
/>
47
</div>
48
</article>
49
</Layout>
50
)
51
}
52
53
const query = groq ` *[_type == "post" && slug.current == $slug][0]{
54
title,
55
"name": author->name,
56
"categories": categories[]->title,
57
mainImage,
58
code,
59
"authorImage": author->image,
60
body,
61
}`
62
63
Post.getInitialProps = async function(context) {
64
65
const {slug = ""} = context.query
66
return await client.fetch(query, { slug })
67
}
68
69
export default Post
70
I really would appreciate some help here! Thanks <3
Advertisement
Answer
You can pass a serializer for the code block type to your BlockContent
using the serializers
prop.
JavaScript
1
20
20
1
const serializers = {
2
types: {
3
code: props => (
4
<pre data-language={props.node.language}>
5
<code>{props.node.code}</code>
6
</pre>
7
)
8
}
9
}
10
11
// ...
12
13
<BlockContent
14
blocks={body}
15
imageOptions={{fit: 'max'}}
16
{client.config()}
17
{code}
18
serializers={serializers}
19
/>
20