Top Method for Incorporating Syntax Highlighting into Code Blocks - React Sanity Blog

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?

Answer №1

If I were to highlight code syntax in my project, I'd opt for the convenient react-syntax-highlighter package available on NPM. Its seamless integration and easy setup make it a user-friendly choice without any complex configurations.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with GMap Compatibility on Specific Web Browsers

I'm currently facing an issue with implementing gMap [1] on a website. The map is functioning properly in Chrome and Safari, but it fails to display in Firefox, IE, and Opera (latest versions of all). I have ensured that the Google Map API key loads a ...

There is an overwhelming amount of dependencies in the Npm package

Recently I delved into the world of npm and found myself facing a conundrum regarding dependencies. While following along with a React tutorial, I was instructed to execute the command: npm install -g create-react-app In addition to that, for a personal ...

React will not acknowledge any incoming requests

I have been working on a project involving an app where I am sending a request and attempting to transmit my data back to react using fetch. Here is what my router file looks like so far: router.get('/', (req, res, next) => { console.log(& ...

What could be causing my React components to not display my CSS styling properly?

If you're developing a React application and integrating CSS for components, ensure that you have included the style-loader and css-loader in your webpack configuration as shown below: module.exports = { mode: 'development', entry: &apo ...

Tips for implementing dynamic routing in React

Currently, I am in the process of building a dashboard application with React. One aspect that is giving me trouble is understanding how to utilize react-router. Can someone provide guidance on utilizing dynamic routes and rendering components? Within my ...

Use include files to wrap content in a div tag

I have a webpage index.html with the following JavaScript scripts: <script type="text/javascript> $(document).ready(function() { $('a.link').click(function() {var url = $(this).attr('href'); $('#content'). ...

Next.js encountered an issue when trying to read properties of null, specifically the 'push' property, resulting in a TypeError

I am utilizing the sweetalert2 library for displaying popups: export default function Home() { const MySwal = withReactContent(Swal) useEffect(() => { MySwal.fire({ showConfirmButton: false, customClass: { ...

Ways to incorporate vector .svg images into a D3js tree diagram

var treeData = [ { "name": "Top Level", "parent": "null", "remark":"yes", "children": [ { "name": "Level 2: A", "parent": "Top Level", "remark":"yes", "children": [ { "name": "So ...

Things, their examples and the impact of setTimeOut

I'm currently delving into object oriented programming in JavaScript. function doStock() { //my class var that = this; var nAntiFreeze = null; // timeout ID var getContent = function(oInPageContainer) { GM_log('Antifreeze, before clea ...

A guide on adding specific rows together in a list

I'm working with a grid that contains various items and I want to calculate the total of the val_itemservico column only for the selected rows, not all of them. How can I achieve this functionality? When the user clicks on the "Calculate" button, I n ...

Enhancing Donut Chart with d3.js

After working for several hours, I'm having trouble getting my d3.js donut graph to update with new data. Here's my HTML: <body> <div id="pie"></div> <script src="pie.js"></script> </body> And he ...

Issue with nested directive not triggering upon page load

I recently started working with AngularJS and came across an issue with nested directives. In my project, I have two directives: MainDir.js (function(){angular.module("mod").directive("mainDir", function(){ return { restrict: "E", scope: {}, ...

Using VBA and Selenium to access iframes within HTML with the #document tag

I am currently facing a challenge in accessing the HTML content within two iframes using Selenium Basic in VBA. Due to restrictions on our machines, we are unable to use IE and other tools like Python are not available to us. In the past, I was able to ac ...

What is the best way to conceal an element by clicking anywhere other than on the element itself?

Currently, I am utilizing jQuery's toggle method to display or hide a page element when another specific page element is clicked. jQuery('a#mobile-search-icon).click(function(){ jQuery('#searchBox').toggle('slow'); }); ...

Setting the value for a HiddenField using jQuery in an ASP.NET application

Is there a way to set a value for a HiddenField control using jQuery? function DisplayContent(obj) { var FareValue = $(obj).closest('tr').find("[id*=lbFare]").text(); $(obj).parent().parent().find('[id*=pnlGrd]').show(); $ ...

How can we effectively transfer a value from TypeScript/Angular?

I am new to TypeScript and Angular, and I'm struggling with assigning a value to a variable within a function and then using that value outside of the function. In regular JavaScript, I would declare the variable first, define its value in the functio ...

Exploring the concepts of AngularJS directives and resources

I've been experimenting with angularjs and rest service calls to display specific data sets, but I'm encountering challenges with custom directives and resources. Currently, I have a custom directive that loads a list of comments in an applicati ...

Encountering a problem with Chrome Extension localization upon installation - receiving an error message claiming default locale was not specified, despite having

Error Message: "The package has been deemed invalid due to the following reason: 'Localization was utilized, however default_locale was not specified in the manifest.' Issue: I have developed a customized extension and defined a default locale, ...

Engaging with JSON data inputs

Need help! I'm attempting to fetch JSON data using AJAX and load it into a select control. However, the process seems to get stuck at "Downloading the recipes....". Any insights on what might be causing this issue? (Tried a few fixes but nothing has w ...

Add delayed event listeners to embedded AJAX request beyond function boundaries

I'm working on developing a custom AJAX method extension named getApi that automatically includes my authentication bearer token in the request header. In my code, there is a function called getToken() which retrieves the token either from sessionSto ...