Skip to content

Instantly share code, notes, and snippets.

@codemile
Created January 2, 2025 16:55
Show Gist options
  • Save codemile/11700eb0df7112a8b314bb2af4257855 to your computer and use it in GitHub Desktop.
Save codemile/11700eb0df7112a8b314bb2af4257855 to your computer and use it in GitHub Desktop.
React functional component to display and syntax-highlight JSON using Prism.js
import Prism from 'prismjs';
import {FC, useEffect, useMemo, useRef} from 'react';
interface JsonBlockProps {
indent?: number;
value: unknown;
}
export const JsonBlock: FC<JsonBlockProps> = ({indent, value}) => {
const ref = useRef<HTMLPreElement>(null);
const jsonStr: string = useMemo(() => {
try {
return Boolean(indent)
? JSON.stringify(value, null, indent)
: JSON.stringify(value);
} catch (e) {
return 'error parsing json';
}
}, [indent, value]);
useEffect(() => {
if (ref.current) {
Prism.highlightElement(ref.current);
}
}, [jsonStr]);
return (
<pre
ref={ref}
className="font-mono overflow-auto border p-4 rounded language-json"
dangerouslySetInnerHTML={{__html: `<code>${jsonStr}</code>`}}
/>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment