Displaying Code Snippets in SolidJS

emee

Emmanuel Ajike

Posted on November 17, 2024

Displaying Code Snippets in SolidJS

The SolidJS ecosystem, while growing, is still relatively small compared to frameworks like React. This can sometimes make it challenging to find tools and solutions specific to SolidJS. Recently, I participated in the #SolidStart2024 hackathon, where I created an app on the SolidStart framework. Through this experience, I encountered a need for a lightweight way to display code snippets within the app.


Introduction

In building my app, I needed to display some code snippets in a readable format, but I didn’t want to add the overhead of a full-fledged code editor like CodeMirror. While CodeMirror is a powerful option, it felt like overkill for simple code block formatting needs. Instead, I found a solution that’s more suitable for the SolidJS ecosystem: Shiki.

💡 Attention SolidJS fans: If you’re a SolidJS or SolidStart enthusiast, we would love your support! Check out our hackathon project, Spotter by Emmanuel Ajike, on SolidHack 2024. Your vote means a lot, and it costs nothing to participate!


API Observability and Spotter.dev

API observability is not the same as logging. With logging, you often have to know in advance what to log and where to look. Observability, on the other hand, provides a full picture of the data flowing through your API, which is crucial for production environments where users rely on your product.

As developers in 2024 and beyond, building robust APIs is critical for delivering real-world solutions. With this in mind, I created Spotter.dev—a developer tool designed to enhance the experience of working with SolidStart REST APIs and microservices. Spotter provides a clean overview of each API endpoint, making it easy to understand the data entering and leaving your services, which ultimately leads to better user experiences.


Using Shiki for Code Highlighting

To format code snippets without the weight of a code editor, I chose Shiki. Shiki is a tool that formats code as HTML, making it simple, intuitive, and easy to use. Here’s a quick example:

const code = `console.log('Shiki is great.')`;

const html = (await codeToHtml(code, {
  lang: "javascript",
  theme: "slack-dark",
})) as string;
Enter fullscreen mode Exit fullscreen mode

In this example, the codeToHtml function takes the code as the first parameter and a configuration object as the second. The configuration specifies the language and theme.

One drawback is that Shiki is asynchronous, which can introduce a delay when rendering code. By using some SolidStart features, we can optimize rendering and minimize this delay:

  • createResource – Fetches the highlighted HTML.
  • onCleanup – Clears any previous HTML content from the wrapper.
  • createEffect – Renders the code.

Here’s the full CodeBlock component I built:

import { codeToHtml } from "shiki";
import { createResource, Suspense, onCleanup, createEffect } from "solid-js";
import { cn } from "~/lib/utils";

const CodeBlock = (props: {
  code: string;
  lang: "json" | "javascript";
  class?: string;
}) => {
  let containerRef!: HTMLDivElement;

  // Fetch the highlighted HTML
  const [html] = createResource(async () => {
    return (await codeToHtml(props.code, {
      lang: props.lang,
      theme: "slack-dark",
    })) as string;
  });

  // Clear previous HTML before setting new content
  onCleanup(() => {
    if (containerRef) containerRef.innerHTML = "";
  });

  // Render the highlighted HTML
  createEffect(() => {
    if (html() && containerRef) {
      containerRef.innerHTML = html() as string;
    }
  });

  return (
    <div
      ref={containerRef}
      class={cn(
        "[&>*]:p-3 [&>*]:rounded-lg [&>*]:font-mono [&>*]:text-sm",
        props.class
      )}
    ></div>
  );
};

export default CodeBlock;
Enter fullscreen mode Exit fullscreen mode

Spotter.dev SolidHack2024


Usage Example

To use the CodeBlock component, simply wrap it with a Suspense component to handle loading states. Here’s an example:

<Suspense fallback={<div>Loading Code</div>}>
  <CodeBlock code={code} lang="json" />
</Suspense>
Enter fullscreen mode Exit fullscreen mode

This approach allows you to display highlighted code snippets with minimal overhead, integrating nicely into the SolidStart framework.


Conclusion

I hope this blog post offers a helpful solution for displaying code snippets in SolidJS. With Shiki, you don’t need the extra weight of Codemirror. Instead, you get a simple, effective tool that meets most needs without overcomplicating your app.

Thank you for reading, and if you find this helpful, please consider supporting our project, Spotter by Emmanuel Ajike, on SolidHack 2024! Your vote would mean a lot to us.

💖 💪 🙅 🚩
emee
Emmanuel Ajike

Posted on November 17, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Displaying Code Snippets in SolidJS
solidhack2024 Displaying Code Snippets in SolidJS

November 17, 2024