I'm currently exploring the most effective method to incorporate syntax highlighting into my react sanity.io blog. Here's a look at the article component I've developed using react:
import React, {useEffect, useState} from "react";
import {useParams} from "react-router-dom";
import sanityClient from "../../client";
import BlockContent from "@sanity/block-content-to-react";
import imageUrlBuilder from "@sanity/image-url";
import Prism from "prismjs";
const builder = imageUrlBuilder(sanityClient);
function urlFor(source) {
return builder.image(source);
}
const serializers = {
types: {
code: (props) => (
<pre data-language={props.node.language}>
<code>{props.node.code}</code>
</pre>
),
},
};
export default function SinglePost() {
const [postData, setPostData] = useState(null);
const {slug} = useParams();
useEffect(() => {
sanityClient
.fetch(
`*[slug.current == $slug]{
title,
slug,
mainImage{
asset->{
_id,
url
}
},
body,
"name": author->name,
"authorImage": author->image
}`,
{slug}
)
.then((data) => setPostData(data[0]))
.catch(console.error);
Prism.highlightAll();
}, [slug]);
if (!postData) return <div>Loading...</div>;
return (
<article>
<h2>{postData.title}</h2>
<div>
<img
src={urlFor(postData.authorImage).width(100).url()}
alt="Author is Kap"
/>
<h4>{postData.name}</h4>
</div>
<img src={urlFor(postData.mainImage).width(200).url()} alt="" />
<div>
<BlockContent
blocks={postData.body}
projectId={sanityClient.clientConfig.projectId}
dataset={sanityClient.clientConfig.dataset}
serializers={serializers}
/>
</div>
</article>
);
}
I am bringing in article data from Sanity and displaying it as a component. I attempted to use prism.js for syntax highlighting but encountered difficulties getting it up and running.
What would be the optimal and most efficient approach to implement syntax highlighting?