Implementing theme in Monaco editor without initializing an instance

I recently developed a web application incorporating Monaco Editor. To enhance user experience, I also integrated Monaco for syntax highlighting in static code blocks.

Following guidance from this source, I successfully implemented syntax highlighting within static code blocks by adding the necessary elements and class names.

An issue I encountered is that the CSS related to this feature only loads when a Monaco editor instance is initialized on a separate page. Consequently, syntax highlighting only functions if a page contains a Monaco editor instance.

To address this challenge, I utilized the following React component for implementing syntax highlighting:

import { editor } from 'monaco-editor';
import React, { ReactElement, useEffect, useRef } from 'react';

interface CodeBlockProps {
  /**
   * The code snippet to display.
   */
  code: string;

  /**
   * The programming language used for code highlighting.
   */
  language: string;
}

/**
 * A component to display code with syntax highlighting using Monaco editor.
 */
export default function CodeBlock({ code, language }: CodeBlockProps): ReactElement {
  const ref = useRef<HTMLPreElement>();

  useEffect(() => {
    if (language) {
      editor.colorizeElement(ref.current, { theme: 'vs' });
    }
  }, [language]);

  return (
    <pre ref={ref} data-lang={language}>
      {code}
    </pre>
  );
}

I'm seeking a solution to prompt Monaco to load the required CSS without necessitating the creation of an editor instance. Any insights or recommendations would be greatly appreciated.

Answer №1

After reading through this particular issue report: https://github.com/microsoft/monaco-editor/issues/1828

I tackled the problem in the following manner:

import React from 'react';
import * as MonacoEditorApi from 'monaco-editor/esm/vs/editor/editor.api';
const { StaticServices } = require('monaco-editor/esm/vs/editor/standalone/browser/standaloneServices');
const { StandaloneThemeServiceImpl } = require('monaco-editor/esm/vs/editor/standalone/browser/standaloneThemeServiceImpl');

export const Viewer: React.FC<{ source: string }> = (props) => {
  // Using a callback ref to receive notification when the element has been mounted
  const viewerRef = (ref: HTMLPreElement) => {
    if (ref) {
      MonacoEditorApi.editor.colorizeElement(ref, { theme: 'vs' });
      const themeService: typeof StandaloneThemeServiceImpl = StaticServices.standaloneThemeService.get();
      themeService.registerEditorContainer(ref);
    }
  };
  return (
    <pre data-lang="yaml" ref={viewerRef}>
      {props.source}
    </pre>
  );
};

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

Tips for splitting JSON objects into individual arrays in React

I'm currently tackling a project that requires me to extract 2 JSON objects into separate arrays for use within the application. I want this process to be dynamic, as there may be varying numbers of objects inside the JSON array in the future - potent ...

An anomaly where a mysterious symbol appears in front of every dollar sign in an HTML document

I have a code written in AngularJS to display the amount in dollars. However, there is an unwanted " Â " character appearing before every " $ " character in the HTML. I am looking for a way to remove this character. Your help is greatly appreciated. Thank ...

Jquery code failing to trigger any response

Recently, I quickly created a jQuery script to dynamically populate a paragraph element in order to easily switch between player and server interaction options. However, I am currently facing an issue where my script does not populate as expected. I have a ...

The scroll function within the inner div is malfunctioning on the Firefox browser

Scrolling within inner div is not functioning properly in the Mozilla Firefox browser. However, it works seamlessly in Chrome. Is there a workaround for enabling scrolling in Firefox? Here is the fiddle link: http://jsfiddle.net/t6jd25x9/2/ body { f ...

NextJS Input Field causing a strange "Hydration Error indicating server HTML should not contain a <div> within a <form>", perplexingly occurring only in Chrome and exclusively on my personal computer

Looking for some assistance with a website I'm working on using NextJS and TailwindCSS. There seems to be a pesky little issue in my code that's causing some trouble. Below is the code snippet for the MainContent section of the page: "use c ...

The database powered by Postgresql performs flawlessly when it comes to updating data with accurate code execution. However, there seems to be an

Imagine a zoo with a postgresql database. To enable web access to this database, I am using php and javascript. Most of the web pages are working fine, but I am currently working on a page where clients can add or remove animals from existing exhibits. T ...

What is the best way to attach a CSS class using an onclick function?

I need to dynamically apply a CSS class to a specific div when clicked using JavaScript. Here is the HTML structure: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv=&qu ...

Retrieving a specific variable from a cookie value that is stored within a JSON array

Is there a way to pass a single variable from a JSON array stored in the qookie file value to JavaScript? The qookie code looks like this: <?php $cookie_key = 'count'; CookieManager::store($cookie_key, json_encode(array( 'SameSite&ap ...

Initial position of jQuery slider

A while back, I came across some slider code on a website and copied it. Unfortunately, I can't seem to locate the source now. Here is the code snippet: slides.min.jquery.js $(function(){ $('#slides').slides({ preload: true, ...

GATSBY: Error: Unable to find the specified property 'includes' within an undefined value

I'm struggling to figure out how to properly filter images in my portfolio website as discussed in this post… Every time I attempt it, I encounter the following error: "TypeError: Cannot read property 'includes' of undefined" D ...

Error: The 'filename' property of undefined cannot be read when attempting to upload a user profile photo using multer

I am facing an issue while attempting to upload a user profile photo using express.js server and Multer. I keep receiving the error message "TypeError: Cannot read property 'filename' of undefined." Below is the code snippets for both the server- ...

The left border is failing to appear on the Td element

When attempting to add border styling to td elements, the left border is not displaying correctly. This issue seems to vary across different browsers. Here is the HTML code: <table class="table-bordered"> <thead> <tr> ...

What is the best way to declare strings within a Typescript interface?

I have an array of Projects with multiple strings in the stack property const projects: IProject[] = [ {name: '', description: '', stack: {'php', 'sql'}} ] What is the best approach for defining the interface? ...

Creating a Fresh Row - Steps to Activate Datepickr on a Copied Row

Whenever a button is pressed, a row in a table duplicates itself. Here is a snippet of the code: <tr> <td valign="top"><input type="text" name="session[]" size="15"></td> <td valign="top"><textarea name="descr[]" cols="40" ...

Remove any objects from the array that have empty values when filtered

I am facing a challenge with filtering objects in an array. Each object contains a title and rows, where the rows also have a risk value (like P1, P2, P3, etc.). My goal is to extract only the rows that have a risk equal to P1 while skipping any objects th ...

Update button text in real-time using JavaScript

I am currently working on a dropdown list that contains 5 elements displayed inside a button when pressed. I want the button to show a default text "Filter by:" before displaying the selected tab value. Additionally, I need the caret symbol to be visible. ...

Eliminate inner margin from the canvas of a bar chart created with ChartJS

I am looking to use Chart.js to create a single stacked bar chart that visualizes progress towards a specific financial goal. I have added a dotted line on top of the chart to represent this goal amount. The issue I am facing is that there is unwanted pad ...

Deleting validation messages from my MVC controls

I set up some validation in my Model by adding the following code: [Required] [StringLength(60, MinimumLength = 4)] [Display(Name = "Users code")] public string UserCode { get; set; } When c ...

What is preventing the exclusion of the null type in this specific situation within Typescript?

type NonNullableCopy<O> = { [p in keyof O] -?: O[p] extends null | undefined ? never : O[p]; }; type Adsa = {a?: number | null} type Basda = NonNullableCopy<Adsa> let asd : Basda = { a: null // Still valid. No errors } Although it see ...

Obtaining the mouse position in JavaScript in relation to the website, preferably without relying on jQuery

I came across this code snippet on Ajaxian, but I am having trouble using cursor.y (or cursor.x) as a variable. When I call the function with it that way, it doesn't seem to work. Could there be a syntax issue or something else causing the problem? f ...