0

I am trying to find the most efficient way to add syntax highlighting to my react sanity.io blog. Here's the article component that I created 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 importing article data from Sanity and rendering it as a component. I tried using prism.js but I am having issues getting it to work.

What's the best and most efficient way to to enable syntax highlighting?

1 Answers1

0

Well, I'd use react-syntax-highlighter package on NPM. It's pretty easy to add to your project. Basically a plug-and-play. With no awkward configurations.

Victor P.
  • 93
  • 1
  • 8