Created
January 2, 2025 16:55
-
-
Save codemile/11700eb0df7112a8b314bb2af4257855 to your computer and use it in GitHub Desktop.
React functional component to display and syntax-highlight JSON using Prism.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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