The function onVisitHighlightedLine is unable to apply a classname when working with Rehype Pretty code

I have integrated Rehype Pretty code into my MDX blog to enhance syntax highlighting. However, I am encountering an issue with getting the line highlighting feature to function properly.

After referring to the documentation and a few other sources, it seems that the configuration below should work, but instead, I'm receiving the following error message.

_mdx_bundler_entry_point-f0976fc3-b34d-45fd-a559-565325298b22.mdx:0:0: ERROR: [plugin: @mdx-js/esbuild] TypeError: Cannot read properties of undefined (reading 'push') at onVisitHighlightedLine

const options = {
    theme: 'one-dark-pro', // 'github-dark-dimmed' is default

    onVisitLine(node) {
        // Prevent lines from collapsing in `display: grid` mode, and allow empty
        if (node.children.length === 0) {
            node.children = [{ type: "text", value: " " }]
        }
    },
    onVisitHighlightedLine(node) {
        node.properties.className.push("line--highlighted");
    },
    onVisitHighlightedWord(node) {
        node.properties.className = ["word--highlighted"]
    },
};

Answer №1

Upon reviewing the log and troubleshooting the node, I discovered that the className was undefined, rendering it non-array status - making the use of the Array.push method impossible. As a solution, I made adjustments to verify if className is indeed an array:

const options = {
    theme: 'one-dark-pro', // 'github-dark-dimmed' is default

    onVisitLine(node) {
        if (node.children.length === 0) {
            // in case of empty line in code block, add space instead of leaving it blank
            node.children = [{ type: "text", value: " " }]
        }
    },
    onVisitHighlightedLine(node) {
        const nodeClass = node.properties.className;
        console.log("Highlighted Line", {node})
        if (nodeClass && nodeClass.length > 0) {
            node.properties.className.push("line--highlighted");
        }else{
            node.properties.className = ["line--highlighted"];
        }
    },
    onVisitHighlightedWord(node) {
        node.properties.className = ["word--highlighted"]
    },
};

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: 502: {“errorMessage”: ” The process exceeded the time limit of 10.01 seconds”} on nextJS website hosted on Netlify

Hello there, I've got a setup with Strapi CMS running on Heroku for the backend, and a NextJS frontend hosted on Netlify. I've been encountering a frustrating issue where my website sometimes displays a 502 error message like this: {“errorMess ...

How can Web3Contract.setProvider("RPC_URL") be replaced in the latest 4.x version of web3-eth-contract?

Is it possible to use this code in web3-eth-contract 1.x? Web3Contract.setProvider("https://rpc2.sepolia.org/") In version 4.x, the setProvider method does not exist in the Web3Contract object. https://i.stack.imgur.com/rQULn.png What is the s ...

The issue of size with 'First Load JS' in Next.js resolved by utilizing immutable.js

Currently in my Next.js v10 project, I am utilizing the immutable library to interact with redux. However, I have come across an optimization issue involving the initial loading of javascript, which appears as "red." While I am still relatively new to thi ...

Having trouble getting Tailwindcss to work with Next.js - what could be causing the configuration issue?

Why is tailwind not displaying correctly in my next.js project? I'm concerned that there might be a problem with my settings. In the styles folder, I have a file called tailwind.css @tailwind base; /* Write your own custom base styles here */ /* S ...

Enhance Your Next.js 14 Website with Custom Meta Tags for Optimized Social Media Previews and Improved Page Load Speed

Currently utilizing Next.js 14, I am seeking to dynamically customize meta tags in order to enhance website previews on platforms such as Discord and Twitter. The metadata that needs to be displayed requires backend calls, which are handled through the gen ...

In React, the clearInterval() function does not effectively clear intervals

Currently, I am implementing the following code: startInterval = () => { this.interval = setInterval(this.intervalFunction, 10000) } stopInterval = () => { clearInterval(this.interval) } However, a problem arises when I invoke the stopInte ...

Encountering ERR_TOO_MANY_REDIRECTS error while deploying my Next.js app on Cloudways hosting platform

My app's page is displaying ERR_TOO_MANY_REDIRECTS This issue only occurs when the site is hosted on cloudways, as it works fine locally. I have tried various solutions but have been unable to identify the cause of the problem. The URL for the sit ...

What is the best way to restrict the input year on @mui/x-date-pickers to a certain range?

Is there a way to restrict the input year range when using @mui/x-date-pickers? I want to limit it from 1000 to 2023 instead of being able to enter years like 0000 or 9999. https://i.stack.imgur.com/0p6j3.jpg I have tried adding a mask to InputProps in my ...

Tips for streamlining responses for the latest create-next-app version

After running npx create-next-app@latest, a series of questions are prompted that disrupt our docker pipeline automation. Is there a way to automate the response to these questions? Currently, we have this command in our Dockerfile: RUN npx --yes create- ...

What is the best way to retain the default value of an MUI form field in Mongoose database?

I am experiencing an issue with my small nextjs app that utilizes an MUI form. The form consists of 2 fields: a default field and an email field. While the email field saves correctly to the database, I am facing difficulties saving the defaultValue field ...

how can I retrieve only the child route in next js?

Need help with this title. This is my Next JS project and I am working on a custom breadcrumb component. Everything seems to be going well so far, but I am facing an issue with the /people page followed by the /people/roles page. I want to extract only the ...

What is the best way to implement OTP expiration time in Next.js using Firebase?

Could anyone please help me with setting the OTP expire time in Next.js using Firebase? I have searched through the Firebase documentation but haven't been able to find a solution to my issue. Below is the code I am using to send the OTP: const appV ...

The error message "FormData parsing error: final boundary is missing" appears due

Recently, I made the switch from node to bun in a Next.js project. However, when trying to parse form data, I encountered this error: 14 | const POST = async (request)=>{ 15 | try { 16 | console.log("request: ", await request.heade ...

The process of seamlessly transferring cookies between the client and server using NextJS server actions

Currently, I am exploring the capabilities of NextJS 14 to see how it could enhance the user experience for our clients. Our existing single-page application (SPA) is quite large and slow to load, with much of it going unused during a typical visit by a cl ...

Managing authentication within getStaticProps requests

I am working on integrating a NextJs application with its backend in Laravel. Currently, all of our API routes in Laravel are secured using Laravel Sanctum to enhance security and prevent cross-site scripting attacks. One challenge I am facing is that th ...

Using package.json to pass variables to the gcp-build method during deployment on Google App Engine

After successfully deploying a Next.js site to Google App Engine, I am trying to figure out how to pass an env_variable to app.yaml in order to set up a production and staging build. Despite going through the GAE documentation, I can't seem to find a ...

How can getStaticPaths be used to define routes?

Imagine you have these 3 route paths stored in an array: const routes = ["route1", "route2", "route3"]; To set up these paths, you would do the following: export async function getStaticPaths() { const routes = ["route1", "route2", "route3"]; const ...

Fetch data asynchronously prior to loading the DOM

Currently in the learning process and facing a hurdle concerning how to retrieve data from an async function and display it in the DOM. The issue I'm encountering is that I am receiving 'undefined' as the DOM gets rendered before the async ...

Having issues with @react-three/drei in next.js environment

Having trouble using drei materials and other features like MeshWobbleMaterial, MeshDistortMaterial, or ContactShadows? You may encounter errors such as: react-three-fiber.esm.js:1383 Uncaught TypeError: Cannot read property 'getState' of null a ...

Building state from multiple child components in Next.js/React: Best Practices

To better illustrate this concept, I suggest checking out this codesandbox link. This is a follow-up to my previous question on Stack Overflow, which can provide additional context. Currently, when interacting with the child elements (such as inputs), th ...