Created
July 1, 2022 07:52
-
-
Save hisui/255518e2fe3ffdbe1e5a4aa07436f153 to your computer and use it in GitHub Desktop.
highlight.js + React
This file contains 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 React, { ReactElement, useMemo } from "react" | |
import hljs from "highlight.js" | |
import 'highlight.js/styles/dark.css' | |
export function Code(props: { lang: string, text: string }): ReactElement { | |
const { value } = useMemo(() => | |
hljs.highlight(props.lang, trimMargin(props.text)), | |
[props.lang, props.text] | |
) | |
return <pre className="hljs"><code dangerouslySetInnerHTML={{ __html: value }} /></pre> | |
} | |
function trimMargin(src: string): string { | |
const rows = src.trimEnd().split("\n") | |
for (let i = 0; i < rows.length; ++i) { | |
const rem = rows[i].trimStart().length | |
if (rem > 0) { | |
const margin = rows[i].length - rem | |
return rows.slice(i).map(e => e.slice(margin)).join("\n") | |
} | |
} | |
return src | |
} |
This file contains 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 React from "react" | |
import { Code } from "./highlight" | |
function Index() { | |
return <div className="container-fluid"> | |
<Code lang="javascript" text={` | |
for (;;) { | |
window.alert("Hello, World!") | |
} | |
`} /> | |
</div> | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment