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

Guide on transmitting information from two separate pages to a PHP script simultaneously using an AJAX request

Looking to gather user information from a form and pass it onto another page smoothly. Origin Site <form action="destination.php" method="post"> Name: <input type="text" name="name"> Email: <input type="text" name="email"> <input typ ...

CSP - Combining React with webpack, styled-components, and Material-UI

After following a guide to implement Content Security Policy (CSP) in my React application, I found that the styles injected by Material-UI and styled-components were not working. Despite my efforts, I couldn't find a solution that didn't involve ...

relocate HTML components

I've been trying to reposition HTML elements within the body of a webpage, but I'm struggling with getting a form tag to appear exactly in the center of the browser - and only that form tag. Can anyone offer guidance or suggest relevant topics fo ...

How can I eliminate padding from events in FullCalendar's timeGrid view?

Is there a way to remove the padding from an event when the calendar is in 'timegridview'? Users are taking advantage of the empty space created, allowing them to bypass a blocked time slot. I currently have it set so that clicking on an event d ...

When examining passwords, Bcrypt returns false

In my application, I am utilizing the Promise interface along with bcrypt. Despite using the same password for comparison, I am receiving a false result. const bcrypt = require('bcrypt'); const saltRounds = 10; const password = 'secret&ap ...

The React application is persistently sending a stream of HTTP requests

Currently, I have a web page that retrieves and displays data from a MongoDb using an API. Users can make modifications to the data on this page, causing it to refresh with the updated information. However, upon inspecting the network requests, I noticed t ...

Approach to Using Bootstrap 4 with Intl-Tel-Input

I've been attempting to integrate intl-tel-input with bootstrap 4, but I'm facing an issue where the placeholder for the input is not showing up. I've tried various solutions found online, but none of them seem to work. Here's my HTML ...

Cleve js does not include delimiters in its date output

In my Vue.js project, I decided to implement a date input field using cleave.js. After passing the following options: options="{date: true, delimiter: '/', datePattern: ['m', 'd', 'Y']}" I encountered an issue wh ...

Utilizing Angular partials within specific views with the assistance of ui-router

I am currently working on developing a MEAN application and facing some challenges while handling ui-router. Within my index.html file, I have set up the template for the entire website including a header, sidebar, and content area where I have placed < ...

Encountering an error with the node module timestampnotes: 'command not recognized'

I am encountering an issue while trying to utilize a npm package called timestamp notes. After executing the following commands: $npm install timestampnotes $timestamp I receive the error message: timestamp:126: command not found: slk Subsequently, I ...

Switch up Google Fusion URL using Jquery

Looking to modify Google Fusion query using jQuery, here is the code snippet: var fusionid= ""; function initMap() { var map = new google.maps.Map(document.getElementById('map-canvas'), { center: {lat: 28.3268, lng: 84.1855}, zoom: 7 } ...

Navigating screen orientation changes in ReactJS

Currently, I am working on a component that needs to update its content based on the screen orientation (portrait/landscape). Here is my approach: var Message = React.createClass({ getInitialState: function() { return {isPortrait: true} } ...

The generation of the npm bin script is not working as expected on Windows operating systems

I'm working on developing an NPM package for command line use. I've set up npm's bin in my package.json to specify the JS file to be executed. Here is a snippet from my package.json: "name": "textree", "bin": { "textree": "./src/cli.js" ...

Error message: Module 'caniuse-lite/dist/unpacker/agents' could not be located while attempting to run create react app

I am in the process of developing a fresh React application using Node version 14.15.3 and npm version 6.14 Encountered Error: Cannot find module 'caniuse-lite/dist/unpacker/agents' The error occurs when executing npx create-react-app Screensho ...

Brother or sister is never empty, as every comment is considered an entity

When going through a list of jQuery objects, I want to verify if the nextSibling attribute is null. However, I found that an HTML comment also counts as a sibling object. How can I address this issue? I am looking for an if statement that will trigger fo ...

Designing a contact form using React and Dynamic Display techniques

The email form will only show an input field for the email address if the age is 17 or above. The input field will have its name attribute set to "email". If the age is less than 17, the email input field will not be displayed. The values entered in the f ...

Display PHP output for a brief moment

Here is the URL: http://www.example.com/?req=welcome. In PHP, to retrieve the parameter req, you can use the following code: echo $_GET['req']; The message will be displayed in the body but it should disappear after one second. What is the be ...

What might be preventing me from achieving a full-length page using height 100% or height 100vh?

I am currently working on a web application that has a similar layout to Slack. I am facing an issue where the page doesn't take up the full width and height as intended. The problem seems to be that it sometimes only occupies half of the screen while ...

When utilizing exit-hook with process.on('SIGTERM'), child_process spawn requires two control-c commands to exit properly

I have the following program running: const { spawn } = require("child_process"); const exitHook = require("exit-hook"); exitHook(() => { console.log("Leaving"); }); spawn("my-program", ["my-args"], { stdio: "inherit" }); // Long running server ...

What is the best way to achieve consistent width in a material-ui card component?

How can I ensure that all these cards have the same width? https://i.stack.imgur.com/Ns3zw.png I'm experiencing an issue with achieving uniform card widths when using flexbox in material-ui. How can I resolve this? Is it necessary to utilize Grid fo ...